markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
tf.string 데이터 타입
텐서플로의 기본 tf.string dtype은 바이트 문자열로 이루어진 텐서를 만듭니다. 유니코드 문자열은 기본적으로 utf-8로 인코딩 됩니다. | tf.constant(u"Thanks 😊") | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.string 텐서는 바이트 문자열을 최소 단위로 다루기 때문에 다양한 길이의 바이트 문자열을 다룰 수 있습니다. 문자열 길이는 텐서 차원(dimensions)에 포함되지 않습니다. | tf.constant([u"You're", u"welcome!"]).shape | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
노트: 파이썬을 사용해 문자열을 만들 때 버전 2와 버전 3에서 유니코드를 다루는 방식이 다릅니다. 버전 2에서는 위와 같이 "u" 접두사를 사용하여 유니코드 문자열을 나타냅니다. 버전 3에서는 유니코드 인코딩된 문자열이 기본값입니다.
유니코드 표현
텐서플로에서 유니코드 문자열을 표현하기 위한 두 가지 방법이 있습니다:
string 스칼라 — 코드 포인트의 시퀀스가 알려진 문자 인코딩을 사용해 인코딩됩니다.
int32 벡터 — 위치마다 개별 코드 포인트를 포함합니다.
예를 들어, 아래의 세 가지 값이 모두 유니코드 문자열 "语言处理"(중국어로 "언어 처리"를 ... | # UTF-8로 인코딩된 string 스칼라로 표현한 유니코드 문자열입니다.
text_utf8 = tf.constant(u"语言处理")
text_utf8
# UTF-16-BE로 인코딩된 string 스칼라로 표현한 유니코드 문자열입니다.
text_utf16be = tf.constant(u"语言处理".encode("UTF-16-BE"))
text_utf16be
# 유니코드 코드 포인트의 벡터로 표현한 유니코드 문자열입니다.
text_chars = tf.constant([ord(char) for char in u"语言处理"])
text_chars | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
표현 간의 변환
텐서플로는 다른 표현으로 변환하기 위한 연산을 제공합니다.
tf.strings.unicode_decode: 인코딩된 string 스칼라를 코드 포인트의 벡터로 변환합니다.
tf.strings.unicode_encode: 코드 포인트의 벡터를 인코드된 string 스칼라로 변환합니다.
tf.strings.unicode_transcode: 인코드된 string 스칼라를 다른 인코딩으로 변환합니다. | tf.strings.unicode_decode(text_utf8,
input_encoding='UTF-8')
tf.strings.unicode_encode(text_chars,
output_encoding='UTF-8')
tf.strings.unicode_transcode(text_utf8,
input_encoding='UTF8',
output_encoding='UTF-... | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
배치(batch) 차원
여러 개의 문자열을 디코딩 할 때 문자열마다 포함된 문자의 개수는 동일하지 않습니다. 반환되는 값은 tf.RaggedTensor로 가장 안쪽 차원의 크기가 문자열에 포함된 문자의 개수에 따라 결정됩니다. | # UTF-8 인코딩된 문자열로 표현한 유니코드 문자열의 배치입니다.
batch_utf8 = [s.encode('UTF-8') for s in
[u'hÃllo', u'What is the weather tomorrow', u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8,
input_encoding='UTF-8')
for sentence_chars in batch... | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.RaggedTensor를 바로 사용하거나, 패딩(padding)을 사용해 tf.Tensor로 변환하거나, tf.RaggedTensor.to_tensor 와 tf.RaggedTensor.to_sparse 메서드를 사용해 tf.SparseTensor로 변환할 수 있습니다. | batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
batch_chars_sparse = batch_chars_ragged.to_sparse() | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
길이가 같은 여러 문자열을 인코딩할 때는 tf.Tensor를 입력으로 사용합니다. | tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [ 99, 111, 119]],
output_encoding='UTF-8') | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
길이가 다른 여러 문자열을 인코딩할 때는 tf.RaggedTensor를 입력으로 사용해야 합니다. | tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8') | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
패딩된 텐서나 희소(sparse) 텐서는 unicode_encode를 호출하기 전에 tf.RaggedTensor로 바꿉니다. | tf.strings.unicode_encode(
tf.RaggedTensor.from_sparse(batch_chars_sparse),
output_encoding='UTF-8')
tf.strings.unicode_encode(
tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1),
output_encoding='UTF-8') | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
유니코드 연산
길이
tf.strings.length 연산은 계산해야 할 길이를 나타내는 unit 인자를 가집니다. unit의 기본 단위는 "BYTE"이지만 인코딩된 string에 포함된 유니코드 코드 포인트의 수를 파악하기 위해 "UTF8_CHAR"나 "UTF16_CHAR"같이 다른 값을 설정할 수 있습니다. | # UTF8에서 마지막 문자는 4바이트를 차지합니다.
thanks = u'Thanks 😊'.encode('UTF-8')
num_bytes = tf.strings.length(thanks).numpy()
num_chars = tf.strings.length(thanks, unit='UTF8_CHAR').numpy()
print('{} 바이트; {}개의 UTF-8 문자'.format(num_bytes, num_chars)) | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
부분 문자열
이와 유사하게 tf.strings.substr 연산은 "unit" 매개변수 값을 사용해 "pos"와 "len" 매개변수로 지정된 문자열의 종류를 결정합니다. | # 기본: unit='BYTE'. len=1이면 바이트 하나를 반환합니다.
tf.strings.substr(thanks, pos=7, len=1).numpy()
# unit='UTF8_CHAR'로 지정하면 4 바이트인 문자 하나를 반환합니다.
print(tf.strings.substr(thanks, pos=7, len=1, unit='UTF8_CHAR').numpy()) | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
유니코드 문자열 분리
tf.strings.unicode_split 연산은 유니코드 문자열의 개별 문자를 부분 문자열로 분리합니다. | tf.strings.unicode_split(thanks, 'UTF-8').numpy() | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
문자 바이트 오프셋
tf.strings.unicode_decode로 만든 문자 텐서를 원본 문자열과 위치를 맞추려면 각 문자의 시작 위치의 오프셋(offset)을 알아야 합니다. tf.strings.unicode_decode_with_offsets은 unicode_decode와 비슷하지만 각 문자의 시작 오프셋을 포함한 두 번째 텐서를 반환합니다. | codepoints, offsets = tf.strings.unicode_decode_with_offsets(u"🎈🎉🎊", 'UTF-8')
for (codepoint, offset) in zip(codepoints.numpy(), offsets.numpy()):
print("바이트 오프셋 {}: 코드 포인트 {}".format(offset, codepoint)) | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
유니코드 스크립트
각 유니코드 코드 포인트는 스크립트(script)라 부르는 하나의 코드 포인트의 집합(collection)에 속합니다. 문자의 스크립트는 문자가 어떤 언어인지 결정하는 데 도움이 됩니다. 예를 들어, 'Б'가 키릴(Cyrillic) 스크립트라는 것을 알고 있으면 이 문자가 포함된 텍스트는 아마도 (러시아어나 우크라이나어 같은) 슬라브 언어라는 것을 알 수 있습니다.
텐서플로는 주어진 코드 포인트가 어떤 스크립트를 사용하는지 판별하기 위해 tf.strings.unicode_script 연산을 제공합니다. 스크립트 코드는 International Com... | uscript = tf.strings.unicode_script([33464, 1041]) # ['芸', 'Б']
print(uscript.numpy()) # [17, 8] == [USCRIPT_HAN, USCRIPT_CYRILLIC] | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.strings.unicode_script 연산은 코드 포인트의 다차원 tf.Tensor나 tf.RaggedTensor에 적용할 수 있습니다: | print(tf.strings.unicode_script(batch_chars_ragged)) | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
예제: 간단한 분할
분할(segmentation)은 텍스트를 단어와 같은 단위로 나누는 작업입니다. 공백 문자가 단어를 나누는 구분자로 사용되는 경우는 쉽지만, (중국어나 일본어 같이) 공백을 사용하지 않는 언어나 (독일어 같이) 단어를 길게 조합하는 언어는 의미를 분석하기 위한 분할 과정이 꼭 필요합니다. 웹 텍스트에는 "NY株価"(New York Stock Exchange)와 같이 여러 가지 언어와 스크립트가 섞여 있는 경우가 많습니다.
스크립트의 변화를 단어 경계로 근사하여 (ML 모델 사용 없이) 대략적인 분할을 수행할 수 있습니다. 위에서 언급된 "NY株価"... | # dtype: string; shape: [num_sentences]
#
# 처리할 문장들 입니다. 이 라인을 수정해서 다른 입력값을 시도해 보세요!
sentence_texts = [u'Hello, world.', u'世界こんにちは'] | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
먼저 문장을 문자 코드 포인트로 디코딩하고 각 문자에 대한 스크립트 식별자를 찾습니다. | # dtype: int32; shape: [num_sentences, (num_chars_per_sentence)]
#
# sentence_char_codepoint[i, j]는
# i번째 문장 안에 있는 j번째 문자에 대한 코드 포인트 입니다.
sentence_char_codepoint = tf.strings.unicode_decode(sentence_texts, 'UTF-8')
print(sentence_char_codepoint)
# dtype: int32; shape: [num_sentences, (num_chars_per_sentence)]
#
# sent... | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
그다음 스크립트 식별자를 사용하여 단어 경계가 추가될 위치를 결정합니다. 각 문장의 시작과 이전 문자와 스크립트가 다른 문자에 단어 경계를 추가합니다. | # dtype: bool; shape: [num_sentences, (num_chars_per_sentence)]
#
# sentence_char_starts_word[i, j]는
# i번째 문장 안에 있는 j번째 문자가 단어의 시작이면 True 입니다.
sentence_char_starts_word = tf.concat(
[tf.fill([sentence_char_script.nrows(), 1], True),
tf.not_equal(sentence_char_script[:, 1:], sentence_char_script[:, :-1])],
... | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
이 시작 오프셋을 사용하여 전체 배치에 있는 단어 리스트를 담은 RaggedTensor를 만듭니다. | # dtype: int32; shape: [num_words, (num_chars_per_word)]
#
# word_char_codepoint[i, j]은
# i번째 단어 안에 있는 j번째 문자에 대한 코드 포인트 입니다.
word_char_codepoint = tf.RaggedTensor.from_row_starts(
values=sentence_char_codepoint.values,
row_starts=word_starts)
print(word_char_codepoint) | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
마지막으로 단어 코드 포인트 RaggedTensor를 문장으로 다시 나눕니다. | # dtype: int64; shape: [num_sentences]
#
# sentence_num_words[i]는 i번째 문장 안에 있는 단어의 수입니다.
sentence_num_words = tf.reduce_sum(
tf.cast(sentence_char_starts_word, tf.int64),
axis=1)
# dtype: int32; shape: [num_sentences, (num_words_per_sentence), (num_chars_per_word)]
#
# sentence_word_char_codepoint[i, j, k]는 i번... | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
최종 결과를 읽기 쉽게 utf-8 문자열로 다시 인코딩합니다. | tf.strings.unicode_encode(sentence_word_char_codepoint, 'UTF-8').to_list() | site/ko/tutorials/load_data/unicode.ipynb | tensorflow/docs-l10n | apache-2.0 |
And to avoid any issues with falling outside the atmosphere grids, we'll set a simple flat limb-darkening model and disable irradiation. | b.set_value_all('ld_mode', 'manual')
b.set_value_all('ld_func', 'linear')
b.set_value_all('ld_coeffs', [0.5])
b.set_value_all('irrad_method', 'none')
b.set_value_all('atm', 'ck2004')
requiv_max = b.get_value('requiv_max', component='primary', context='component')
requiv_max_factors = np.arange(0.3,1.0,0.05)
sb_pblum_... | 2.3/examples/pblum_method_compare.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Here we can see that Stefan-Boltzmann (which assumes spherical stars) is an increasingly bad approximation as the distortion of the star increase (as expected). But even in the quite detached case, the luminosities are not in great agreement. For this reason it is important to not trust absolute pblum values when usi... | _ = plt.plot(requiv_max_factors, sb_pblum_abs, 'k-', label='Stefan-Boltzmann')
_ = plt.plot(requiv_max_factors, ph_pblum_abs, 'b-', label='PHOEBE mesh')
_ = plt.xlabel('requiv / requiv_max')
_ = plt.ylabel('L (W)')
_ = plt.legend() | 2.3/examples/pblum_method_compare.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Basic Pie Chart | data = np.random.rand(3)
pie = Pie(sizes=data, display_labels="outside", labels=list(string.ascii_uppercase))
fig = Figure(marks=[pie], animation_duration=1000)
fig | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Update Data | n = np.random.randint(1, 10)
pie.sizes = np.random.rand(n) | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Display Values | with pie.hold_sync():
pie.display_values = True
pie.values_format = ".1f" | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Enable sort | pie.sort = True | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Set different styles for selected slices | pie.selected_style = {"opacity": 1, "stroke": "white", "stroke-width": 2}
pie.unselected_style = {"opacity": 0.2}
pie.selected = [1]
pie.selected = None | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
For more on piechart interactions, see the Mark Interactions notebook
Modify label styling | pie.label_color = "Red"
pie.font_size = "20px"
pie.font_weight = "bold" | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Update pie shape and style | pie1 = Pie(sizes=np.random.rand(6), inner_radius=0.05)
fig1 = Figure(marks=[pie1], animation_duration=1000)
fig1 | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Change pie dimensions | # As of now, the radius sizes are absolute, in pixels
with pie1.hold_sync():
pie1.radius = 150
pie1.inner_radius = 100
# Angles are in radians, 0 being the top vertical
with pie1.hold_sync():
pie1.start_angle = -90
pie1.end_angle = 90 | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Move the pie around
x and y attributes control the position of the pie in the figure.
If no scales are passed for x and y, they are taken in absolute
figure coordinates, between 0 and 1. | pie1.y = 0.1
pie1.x = 0.6
pie1.radius = 180 | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Change slice styles
Pie slice colors cycle through the colors and opacities attribute, as the Lines Mark. | pie1.stroke = "brown"
pie1.colors = ["orange", "darkviolet"]
pie1.opacities = [0.1, 1]
fig1 | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Represent an additional dimension using Color
The Pie allows for its colors to be determined by data, that is passed to the color attribute.
A ColorScale with the desired color scheme must also be passed. | from bqplot import ColorScale, ColorAxis
Nslices = 7
size_data = np.random.rand(Nslices)
color_data = np.random.randn(Nslices)
sc = ColorScale(scheme="Reds")
# The ColorAxis gives a visual representation of its ColorScale
ax = ColorAxis(scale=sc)
pie2 = Pie(sizes=size_data, scales={"color": sc}, color=color_data)
Fi... | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
Position the Pie using custom scales
Pies can be positioned, via the x and y attributes,
using either absolute figure scales or custom 'x' or 'y' scales | from datetime import datetime
from bqplot.traits import convert_to_date
from bqplot import DateScale, LinearScale, Axis
avg_precipitation_days = [
(d / 30.0, 1 - d / 30.0) for d in [2, 3, 4, 6, 12, 17, 23, 22, 15, 4, 1, 1]
]
temperatures = [9, 12, 16, 20, 22, 23, 22, 22, 22, 20, 15, 11]
dates = [datetime(2010, k,... | examples/Marks/Object Model/Pie.ipynb | bloomberg/bqplot | apache-2.0 |
We can now load the weights into Python: | try:
import cPickle as pickle
except ImportError:
# Python 3
import pickle
with open('vgg16.pkl', 'rb') as f:
model = pickle.load(f, encoding='latin-1')
else:
# Python 2
with open('vgg16.pkl', 'rb') as f:
model = pickle.load(f)
weights = model['param values'] # list of network ... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
And define and fill the VGG-16 network in Lasagne: | import lasagne
from lasagne.layers import InputLayer, DenseLayer, NonlinearityLayer
from lasagne.layers.dnn import Conv2DDNNLayer as ConvLayer
from lasagne.layers import Pool2DLayer as PoolLayer
from lasagne.nonlinearities import softmax
net = {}
net['input'] = InputLayer((None, 3, 224, 224))
net['conv1_1'] = ConvLaye... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
VGG-16 needs the input image in a specific size (224x224) and format (BGR instead of RGB). We'll define a helper function to download and convert an image (original source): | import numpy as np
import matplotlib.pyplot as plt
%config InlineBackend.figure_format = 'jpeg'
%matplotlib inline
import urllib
import io
import skimage.transform
def prepare_image(url):
ext = url.rsplit('.', 1)[1]
img = plt.imread(io.BytesIO(urllib.urlopen(url).read()), ext)
# Resize so smallest dim = 25... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Computing a saliency map
Now that we've got the basics in place, let's define a function to compute a saliency map. As mentioned in the introduction, the main idea is to compute the gradient of the output with respect to the input. More specifically, we are interested in the gradient of the predicted class, that is, th... | import theano
import theano.tensor as T
def compile_saliency_function(net):
"""
Compiles a function to compute the saliency maps and predicted classes
for a given minibatch of input images.
"""
inp = net['input'].input_var
outp = lasagne.layers.get_output(net['fc8'], deterministic=True)
max... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Let us also define a helper function for plotting an input image along with the saliency map. We will display three variants:
The magnitude per pixel, taking the maximum magnitude over the three color channels, as in [2], Section 3.1
The positive magnitudes (positively correlated with the output), keeping color inform... | def show_images(img_original, saliency, max_class, title):
# get out the first map and class from the mini-batch
saliency = saliency[0]
max_class = max_class[0]
# convert saliency from BGR to RGB, and from c01 to 01c
saliency = saliency[::-1].transpose(1, 2, 0)
# plot the original image and the ... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Simonyan et al. (2013): Plain Gradient
Reference [2] uses the unmodified gradient to compute the saliency map, so this is what we will start with. We will prepare one of the ILSVRC2012 validation images to feed to the network: | url = 'http://farm5.static.flickr.com/4064/4334173592_145856d89b.jpg'
img_original, img = prepare_image(url) | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Then we'll compile the saliency map function, pass the image through it and display the results: | saliency_fn = compile_saliency_function(net)
saliency, max_class = saliency_fn(img)
show_images(img_original, saliency, max_class, "default gradient") | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
As in the original paper (Figure 2), the gradient magnitudes roughly show which pixels are relevant for the network predicting "green snake", i.e., where in the picture the detected green snake is visible. But we can do better!
Springenberg et al. (2015): Guided Backpropagation
Reference [3] proposes to change a tiny d... | class ModifiedBackprop(object):
def __init__(self, nonlinearity):
self.nonlinearity = nonlinearity
self.ops = {} # memoizes an OpFromGraph instance per tensor type
def __call__(self, x):
# OpFromGraph is oblique to Theano optimizations, so we need to move
# things to GPU ourse... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
We can now define a subclass that does guided backpropagation through a nonlinearity: | class GuidedBackprop(ModifiedBackprop):
def grad(self, inputs, out_grads):
(inp,) = inputs
(grd,) = out_grads
dtype = inp.dtype
return (grd * (inp > 0).astype(dtype) * (grd > 0).astype(dtype),) | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Finally, we replace all the nonlinearities of the network: | relu = lasagne.nonlinearities.rectify
relu_layers = [layer for layer in lasagne.layers.get_all_layers(net['prob'])
if getattr(layer, 'nonlinearity', None) is relu]
modded_relu = GuidedBackprop(relu) # important: only instantiate this once!
for layer in relu_layers:
layer.nonlinearity = modded_relu | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
We can now recompile the saliency map function, and compute and display the saliency maps: | saliency_fn = compile_saliency_function(net)
saliency, max_class = saliency_fn(img)
show_images(img_original, saliency, max_class, "guided backprop") | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
As in [3], Appendix C, they are considerably more detailed. We can see that the eye is important for the prediction: making its green part black or its black part green would reduce the output activation the most. Note that for guided backpropagation, the negative saliency values only arise from the very first convolut... | class ZeilerBackprop(ModifiedBackprop):
def grad(self, inputs, out_grads):
(inp,) = inputs
(grd,) = out_grads
#return (grd * (grd > 0).astype(inp.dtype),) # explicitly rectify
return (self.nonlinearity(grd),) # use the given nonlinearity | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
And again, we'll modify the network, recompile the saliency map function, compute and display the saliency maps: | modded_relu = ZeilerBackprop(relu)
for layer in relu_layers:
layer.nonlinearity = modded_relu
saliency_fn = compile_saliency_function(net)
saliency, max_class = saliency_fn(img)
show_images(img_original, saliency, max_class, "deconvnet") | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
This is pretty much in line with [3], Appendix C, Figure 5: The DeconvNet reconstructs sharper features than the default gradient, but fails to correctly localize those features in the input image.
Bonus Image
For some images, even the unmodified gradient is largely uninformative, while guided backpropagation works rem... | url = 'http://farm6.static.flickr.com/5066/5595774449_b3f85b36ec.jpg'
img_original, img = prepare_image(url)
for layer in relu_layers:
layer.nonlinearity = relu
saliency_fn = compile_saliency_function(net)
show_images(img_original, *saliency_fn(img), title="default gradient")
modded_relu = GuidedBackprop(relu)
for... | examples/Saliency Maps and Guided Backpropagation.ipynb | 317070/ModelZoo | mit |
Classwork 3
Michael Seaman, Chinmai Raman, Austin Ayers, Taylor Patti
Organized by Andrew Malfavon
Excercise A.2: Computing $\pi$ via sequences
Michael Seaman
The following sequences all converge to pi, although at different rates.
In order:
$$a_n = 4\sum_{k=1}^{n}\frac{(-1)^{k+1}}{2k-1}$$
$$b_n = (6\sum_{k=1}^{n}k^{-2... | n = 30
plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fa),'g.')
plt.show()
plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fb) ** .5 ,'b.')
plt.show()
plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fc) ** .25 ,'y.')
plt.show()
plt.plot([x for x in range(n)],p3.pi_sequence(n, p3.fd),'r.')
plt.show()
pl... | cw-3.ipynb | chapman-phys227-2016s/cw-3-classwork-team | mit |
Chinmai Raman
Classwork 3
5.49 Experience Overflow in a Function
Calculates an exponential function and returns the numerator, denominator and the fraction as a 3-tuple | x = np.linspace(0,1,10000)
y1 = p1.v(x, 1, np.exp)[2]
y2 = p1.v(x, 0.1, np.exp)[2]
y3 = p1.v(x, 0.01, np.exp)[2]
fig = plt.figure(1)
plt.plot(x, y1, 'b')
plt.plot(x, y2, 'r')
plt.plot(x, y3, 'g')
plt.xlabel('x')
plt.ylabel('v(x)')
plt.legend(['(1 - exp(x / mu)) / (1 - exp(1 / mu))'])
plt.axis([x[0], x[-1], min(y3), ma... | cw-3.ipynb | chapman-phys227-2016s/cw-3-classwork-team | mit |
Austin Ayers
Classwork 3
A.1 Determine the limit of a sequence
Computes and returns the following sequence for N = 100
$$a_n = \frac{7+1/(n+1)}{3-1/(n+1)^2}, \qquad n=0,1,2,\ldots,N$$ | p2.part_a()
p2.part_b()
p2.part_c()
p2.part_d()
p2.part_e()
p2.part_f() | cw-3.ipynb | chapman-phys227-2016s/cw-3-classwork-team | mit |
diffeq_midpoint
Taylor Patti
Uses the midpoint integration rule along with numpy vectors to produce a continuous vector which gives integral data for an array of prespecified points.
Here we use it to integrate sin from 0 to pi. | function_call = p4.vector_midpoint(p4.np.sin, 0, p4.np.pi, 10000)
print function_call[1][-1] | cw-3.ipynb | chapman-phys227-2016s/cw-3-classwork-team | mit |
Observe the close adherance to the actual value of this cannonical value.
We can also call it at a different value of x. Let's look at the value of this integral from 0 to pi over 2. Again, the result will have strikingly close adherance to the analytical value of this integral. | print function_call[1][5000] | cw-3.ipynb | chapman-phys227-2016s/cw-3-classwork-team | mit |
2. Delegating Iterator | # if you write a container class, and want to expose an iterator over an internal collection use the __iter()__ method
class Node:
def __init__(self):
self._children = [1,2,3]
def __iter__(self):
return iter(self._children)
root = Node()
for x in root:
print(x) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
3. Map
map applies a function to every element of a sequence and returns an iterator of elements | simpsons = ['homer', 'marge', 'bart']
map(len, simpsons) # returns [0, 2, 4]
#equivalent list comprehension
[len(word) for word in simpsons]
map(lambda word: word[-1], simpsons) # returns ['r','e', 't']
#equivalent list comprehension
[word[-1] for word in simpsons] | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
4. Filter
filter returns an iterator containing the elements from a sequence for which a condition is True: | nums = range(5)
filter(lambda x: x % 2 == 0, nums) # returns [0, 2, 4]
# equivalent list comprehension
[num for num in nums if num % 2 == 0] | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
5. Named Slices | ###### 0123456789012345678901234567890123456789012345678901234567890'
record = '....................100 .......513.25 ..........'
SHARES = slice(20,32)
PRICE = slice(40,48)
cost = int(record[SHARES]) * float(record[PRICE])
cost | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
6. zip | # zip() allows you to create an iterable view over a tuple created out of two separate iterable views
prices = { 'ACME' : 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ' : 37.20, 'FB' : 10.75 }
min_price = min(zip(prices.values(), prices.keys())) #(10.75, 'FB')
max((zip(prices.values(), prices.keys()))) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
zip can only be iterated over once! | prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names))
# running the following code would fail
#print(min(prices_and_names))
# zip usually stops when any individual iterator ends (it iterates only until the end of the shortest sequence)
a = [1, 2, 3]
b = ['w', 'x', 'y', 'z']
for i in zip... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
7. itemgetter | from operator import itemgetter
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_fname
row... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
8. attrgetter | from operator import attrgetter
#used to sort objects that dont natively support comparison
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
users = [User(23), User(3), User(99)]
users
sorted(users, key=attrgett... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
9. groupby
The groupby() function works by scanning a sequence and finding sequential “runs”
of identical values (or values returned by the given key function). On each iteration, it
returns the value along with an iterator that produces all of the items in a group with
the same value. | from operator import itemgetter
from itertools import groupby
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
10. Generator Expressions | mylist = [1, 4, -5, 10, -7, 2, 3, -1]
positives = (n for n in mylist if n > 0)
positives
for x in positives:
print(x)
nums = [1, 2, 3, 4, 5]
sum(x * x for x in nums)
# Output a tuple as CSV
s = ('ACME', 50, 123.45)
','.join(str(x) for x in s)
# Determine if any .py files exist in a directory
import os
files = ... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
11. compress
itertools.compress() takes an iterable and an accompanying Boolean selector sequence as input. As output, it gives you all of the items in the iterable where the corresponding element in the selector is True. | from itertools import compress
addresses = [
'5412 N CLARK',
'5148 N CLARK',
'5800 E 58TH',
'2122 N CLARK'
'5645 N RAVENSWOOD',
'1060 W ADDISON',
'4801 N BROADWAY',
'1039 W GRANVILLE',
]
counts = [ 0, 3, 10, 4, 1, 7, 6, 1]
more5 = [n > 5 for n in counts]
more5
list(compress(addresses, more5)) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
12. reversed | #iterates in reverse
a = [1, 2, 3, 4]
for x in reversed(a):
print(x)
#you can customize the behavior of reversed for your class by implementing __reversed()__ method
class Counter:
def __init__(self, start):
self.start = start
# Forward iterator
def __iter__(self):
n = 1
while n... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
13. Generators with State | # To expose state available at each step of iteration, use a classs that implements __iter__()
class countingiterator:
def __init__(self, items):
self.items=items
def __iter__(self):
self.clear_count()
for item in self.items:
self.count+=1
yield item
def clear... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
14. islice and dropwhile | # itertools.islice allows slicing of iterators
def count(n):
while True:
yield n
n += 1
c=count(0)
#the next line would fail
# c[10:20]
import itertools
for x in itertools.islice(c,10,15):
print(x)
c=count(0)
for x in itertools.islice(c, 10, 15, 2):
print(x)
# if you don't know how many t... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
15. Permutations and Combinations of Elements | from itertools import permutations
items = ['a', 'b', 'c']
for p in permutations(items):
print(p)
# for smaller subset permutations
for p in permutations(items,2):
print(p)
# itertools.combinations ignores element order in creating unique sets
from itertools import combinations
for c in combinations(items, ... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
16. Iterating with Indexes | # enumerate returns the iterated item and an index
my_list = ['a', 'b', 'c']
for idx, val in enumerate(my_list):
print(idx, val)
# pass a starting index to enumerate
for idx, val in enumerate(my_list, 7):
print(idx, val) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
17. chain | # chain iterates over several sequences, one after the other
# making them look like one long sequence
from itertools import chain
a = [1, 2]
b = ['x', 'y', 'z']
for x in chain(a, b):
print(x) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
18. Flatten a Nested Sequence | # you want to traverse a sequence with nested sub sequences as one big sequence
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types): # ignore types treats iterable string/bytes as simple values
... | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
19. Merging Presorted Iterables | import heapq
a = [1, 4, 7]
b = [2, 5, 6]
for c in heapq.merge(a, b):
print(c) | Python Quick Reference/Data Algorithms.ipynb | eriksalt/jupyter | mit |
WWW Data download
http://www3.nd.edu/~networks/resources.htm
World-Wide-Web: [README] [DATA]
Réka Albert, Hawoong Jeong and Albert-László Barabási:
Diameter of the World Wide Web Nature 401, 130 (1999) [ PDF ]
作业:
下载www数据
构建networkx的网络对象g(提示:有向网络)
将www数据添加到g当中
计算网络中的节点数量和链接数量 | G = nx.Graph()
n = 0
with open ('/Users/chengjun/bigdata/www.dat.gz.txt') as f:
for line in f:
n += 1
if n % 10**4 == 0:
flushPrint(n)
x, y = line.rstrip().split(' ')
G.add_edge(x,y)
nx.info(G) | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
描述网络
nx.karate_club_graph
我们从karate_club_graph开始,探索网络的基本性质。 | G = nx.karate_club_graph()
clubs = [G.node[i]['club'] for i in G.nodes()]
colors = []
for j in clubs:
if j == 'Mr. Hi':
colors.append('r')
else:
colors.append('g')
nx.draw(G, with_labels = True, node_color = colors)
G.node[1] # 节点1的属性
G.edge.keys()[:3] # 前三条边的id
nx.info(G)
G.nodes()[:10... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
网络直径 | nx.diameter(G)#返回图G的直径(最长最短路径的长度) | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
密度 | nx.density(G)
nodeNum = len(G.nodes())
edgeNum = len(G.edges())
2.0*edgeNum/(nodeNum * (nodeNum - 1)) | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
作业:
计算www网络的网络密度
聚集系数 | cc = nx.clustering(G)
cc.items()[:5]
plt.hist(cc.values(), bins = 15)
plt.xlabel('$Clustering \, Coefficient, \, C$', fontsize = 20)
plt.ylabel('$Frequency, \, F$', fontsize = 20)
plt.show() | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
Spacing in Math Mode
In a math environment, LaTeX ignores the spaces you type and puts in the spacing that it thinks is best. LaTeX formats mathematics the way it's done in mathematics texts. If you want different spacing, LaTeX provides the following four commands for use in math mode:
\; - a thick space
\: - a medium... | # M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003
nx.degree_assortativity_coefficient(G) #计算一个图的度匹配性。
Ge=nx.Graph()
Ge.add_nodes_from([0,1],size=2)
Ge.add_nodes_from([2,3],size=3)
Ge.add_edges_from([(0,1),(2,3)])
print(nx.numeric_assortativity_coefficient(Ge,'size'))
# plot degree corr... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
Degree centrality measures.(度中心性)
degree_centrality(G) # Compute the degree centrality for nodes.
in_degree_centrality(G) # Compute the in-degree centrality for nodes.
out_degree_centrality(G) # Compute the out-degree centrality for nodes.
closeness_centrality(G[, v, weighted_edges]) # Compute closene... | dc = nx.degree_centrality(G)
closeness = nx.closeness_centrality(G)
betweenness= nx.betweenness_centrality(G)
fig = plt.figure(figsize=(15, 4),facecolor='white')
ax = plt.subplot(1, 3, 1)
plt.hist(dc.values(), bins = 20)
plt.xlabel('$Degree \, Centrality$', fontsize = 20)
plt.ylabel('$Frequency, \, F$', fontsize = 20... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
度分布 | from collections import defaultdict
import numpy as np
def plotDegreeDistribution(G):
degs = defaultdict(int)
for i in G.degree().values(): degs[i]+=1
items = sorted ( degs.items () )
x, y = np.array(items).T
plt.plot(x, y, 'b-o')
plt.xscale('log')
plt.yscale('log')
plt.legend(['Degree'... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
网络科学理论简介
网络科学:分析网络结构
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
规则网络 | import networkx as nx
import matplotlib.pyplot as plt
RG = nx.random_graphs.random_regular_graph(3,200) #生成包含20个节点、每个节点有3个邻居的规则图RG
pos = nx.spectral_layout(RG) #定义一个布局,此处采用了spectral布局方式,后变还会介绍其它布局方式,注意图形上的区别
nx.draw(RG,pos,with_labels=False,node_size = 30) #绘制规则图的图形,with_labels决定节点是非带标签(编号),node_size是节点的直径
p... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
ER随机网络 | import networkx as nx
import matplotlib.pyplot as plt
ER = nx.random_graphs.erdos_renyi_graph(200,0.05) #生成包含20个节点、以概率0.2连接的随机图
pos = nx.shell_layout(ER) #定义一个布局,此处采用了shell布局方式
nx.draw(ER,pos,with_labels=False,node_size = 30)
plt.show()
plotDegreeDistribution(ER) | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
小世界网络 | import networkx as nx
import matplotlib.pyplot as plt
WS = nx.random_graphs.watts_strogatz_graph(200,4,0.3) #生成包含200个节点、每个节点4个近邻、随机化重连概率为0.3的小世界网络
pos = nx.circular_layout(WS) #定义一个布局,此处采用了circular布局方式
nx.draw(WS,pos,with_labels=False,node_size = 30) #绘制图形
plt.show()
plotDegreeDistribution(WS)
nx.diameter(... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
BA网络 | import networkx as nx
import matplotlib.pyplot as plt
BA= nx.random_graphs.barabasi_albert_graph(200,2) #生成n=20、m=1的BA无标度网络
pos = nx.spring_layout(BA) #定义一个布局,此处采用了spring布局方式
nx.draw(BA,pos,with_labels=False,node_size = 30) #绘制图形
plt.show()
plotDegreeDistribution(BA)
BA= nx.random_graphs.barabasi_albert_gr... | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
作业:
阅读 Barabasi (1999) Internet Diameter of the world wide web.Nature.401
绘制www网络的出度分布、入度分布
使用BA模型生成节点数为N、幂指数为$\gamma$的网络
计算平均路径长度d与节点数量的关系
<img src = './img/diameter.png' width = 10000> | Ns = [i*10 for i in [1, 10, 100, 1000]]
ds = []
for N in Ns:
print N
BA= nx.random_graphs.barabasi_albert_graph(N,2)
d = nx.average_shortest_path_length(BA)
ds.append(d)
plt.plot(Ns, ds, 'r-o')
plt.xlabel('$N$', fontsize = 20)
plt.ylabel('$<d>$', fontsize = 20)
plt.xscale('log')
plt.show() | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
More
http://computational-communication.com/wiki/index.php?title=Networkx | # subgraph
G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
G.add_path([0,1,2,3])
H = G.subgraph([0,1,2])
G.edges(), H.edges() | code/16&17networkx.ipynb | Aggieyixin/cjc2016 | mit |
Set your bucket: | BUCKET = # REPLACE BY YOUR BUCKET
os.environ['BUCKET'] = BUCKET | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Verify CSV files exist
In the seventh lab of this series 1b_prepare_data_babyweight, we sampled from BigQuery our train, eval, and test CSV files. Verify that they exist, otherwise go back to that lab and create them. | TRAIN_DATA_PATH = "gs://{bucket}/babyweight/data/train*.csv".format(bucket=BUCKET)
EVAL_DATA_PATH = "gs://{bucket}/babyweight/data/eval*.csv".format(bucket=BUCKET)
!gsutil ls $TRAIN_DATA_PATH
!gsutil ls $EVAL_DATA_PATH | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create Keras model
Lab Task #1: Set CSV Columns, label column, and column defaults.
Now that we have verified that our CSV files exist, we need to set a few things that we will be using in our input function.
* CSV_COLUMNS are going to be our header names of our columns. Make sure that they are in the same order as in ... | # Determine CSV, label, and key columns
# TODO: Create list of string column headers, make sure order matches.
CSV_COLUMNS = [""]
# TODO: Add string name for label column
LABEL_COLUMN = ""
# Set default values for each CSV column as a list of lists.
# Treat is_male and plurality as strings.
DEFAULTS = [] | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #2: Make dataset of features and label from CSV files.
Next, we will write an input_fn to read the data. Since we are reading from CSV files we can save ourself from trying to recreate the wheel and can use tf.data.experimental.make_csv_dataset. This will create a CSV dataset object. However we will need to di... | def features_and_labels(row_data):
"""Splits features and labels from feature dictionary.
Args:
row_data: Dictionary of CSV column names and tensor values.
Returns:
Dictionary of feature tensors and label tensor.
"""
label = row_data.pop(LABEL_COLUMN)
return row_data, label # ... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #3: Create input layers for raw features.
We'll need to get the data read in by our input function to our model function, but just how do we go about connecting the dots? We can use Keras input layers (tf.Keras.layers.Input) by defining:
* shape: A shape tuple (integers), not including the batch size. For inst... | def create_input_layers():
"""Creates dictionary of input layers for each feature.
Returns:
Dictionary of `tf.Keras.layers.Input` layers for each feature.
"""
# TODO: Create dictionary of tf.keras.layers.Input for each dense feature
deep_inputs = {}
# TODO: Create dictionary of tf.kera... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #4: Create feature columns for inputs.
Next, define the feature columns. mother_age and gestation_weeks should be numeric. The others, is_male and plurality, should be categorical. Remember, only dense feature columns can be inputs to a DNN. | def create_feature_columns(nembeds):
"""Creates wide and deep dictionaries of feature columns from inputs.
Args:
nembeds: int, number of dimensions to embed categorical column down to.
Returns:
Wide and deep dictionaries of feature columns.
"""
# TODO: Create deep feature columns fo... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #5: Create wide and deep model and output layer.
So we've figured out how to get our inputs ready for machine learning but now we need to connect them to our desired output. Our model architecture is what links the two together. We need to create a wide and deep model now. The wide side will just be a linear r... | def get_model_outputs(wide_inputs, deep_inputs, dnn_hidden_units):
"""Creates model architecture and returns outputs.
Args:
wide_inputs: Dense tensor used as inputs to wide side of model.
deep_inputs: Dense tensor used as inputs to deep side of model.
dnn_hidden_units: List of integers ... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #6: Create custom evaluation metric.
We want to make sure that we have some useful way to measure model performance for us. Since this is regression, we would like to know the RMSE of the model on our evaluation dataset, however, this does not exist as a standard evaluation metric, so we'll have to create our ... | def rmse(y_true, y_pred):
"""Calculates RMSE evaluation metric.
Args:
y_true: tensor, true labels.
y_pred: tensor, predicted labels.
Returns:
Tensor with value of RMSE between true and predicted labels.
"""
# TODO: Calculate RMSE from true and predicted labels
pass | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #7: Build wide and deep model tying all of the pieces together.
Excellent! We've assembled all of the pieces, now we just need to tie them all together into a Keras Model. This is NOT a simple feedforward model with no branching, side inputs, etc. so we can't use Keras' Sequential Model API. We're instead goin... | def build_wide_deep_model(dnn_hidden_units=[64, 32], nembeds=3):
"""Builds wide and deep model using Keras Functional API.
Returns:
`tf.keras.models.Model` object.
"""
# Create input layers
inputs = create_input_layers()
# Create feature columns
wide_fc, deep_fc = create_feature_co... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
We can visualize the wide and deep network using the Keras plot_model utility. | tf.keras.utils.plot_model(
model=model, to_file="wd_model.png", show_shapes=False, rankdir="LR") | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Run and evaluate model
Lab Task #8: Train and evaluate.
We've built our Keras model using our inputs from our CSV files and the architecture we designed. Let's now run our model by training our model parameters and periodically running an evaluation to track how well we are doing on outside data as training goes on. We... | TRAIN_BATCH_SIZE = 32
NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset repeats, it'll wrap around
NUM_EVALS = 5 # how many times to evaluate
# Enough to get a reasonable sample, but not so much that it slows down
NUM_EVAL_EXAMPLES = 10000
# TODO: Load training dataset
trainds = load_dataset()
# TODO: Load evaluati... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Visualize loss curve | # Plot
nrows = 1
ncols = 2
fig = plt.figure(figsize=(10, 5))
for idx, key in enumerate(["loss", "rmse"]):
ax = fig.add_subplot(nrows, ncols, idx+1)
plt.plot(history.history[key])
plt.plot(history.history["val_{}".format(key)])
plt.title("model {}".format(key))
plt.ylabel(key)
plt.xlabel("epoch"... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Save the model | OUTPUT_DIR = "babyweight_trained_wd"
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
EXPORT_PATH = os.path.join(
OUTPUT_DIR, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
tf.saved_model.save(
obj=model, export_dir=EXPORT_PATH) # with default serving function
print("Exported trained model to {}".format(EXPORT... | courses/machine_learning/deepdive2/structured/labs/4c_keras_wide_and_deep_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.