markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values | hash
stringlengths 32
32
|
---|---|---|---|---|---|
Creating a table
From here we need to create a first table. Let's recreate the Person table from the SW Carpentry db lesson, topic 1. | %%sql
CREATE TABLE Person
(ident CHAR(10),
personal CHAR(25),
family CHAR(25));
%sql SHOW TABLES;
%sql DESCRIBE Person; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | c52d8668503750e41fdab243eaaac393 |
Inserting data
Okay then, let's insert the sample data: | %%sql
INSERT INTO Person VALUES
("dyer", "William", "Dyer"),
("pb", "Frank", "Pabodie"),
("lake", "Anderson", "Lake"),
("roe", "Valentina", "Roerich"),
("danforth", "Frank", "Danforth")
; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | bfe5128d0f9506bbbd4d3fb7718131b2 |
Selecting data
Okay, now we're cooking. There's data in the Person table, so we can start to SELECT it. | %sql SELECT * FROM Person;
%sql SELECT * FROM Person WHERE personal = "Frank"; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | 329c5d7e2960cd6650cbfbdf5c1fdeca |
Accessing data from Python
One of the great things about ipython-sql is it marshalls all the data into Python objects for you. For example, to get the result data into a Python object, grab it from _: | result = _
print result | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | 1cc0b837efd2a4f7e9cd81fd25f56080 |
You can even assign it to a Pandas dataframe: | df = result.DataFrame()
df | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | c98be037493afd1286283741d6447b72 |
Cleaning up
If you were just doing a little exploring and wish to clean up, it's easy to get rid of tables and databases.
NOTE: these are permanent actions. Only do them if you know you don't need them any longer.
To get rid of a table, use DROP TABLE: | %sql DROP TABLE Person;
%sql SHOW TABLES; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | b35ae69f9be22eb559b2ac3b4bb3e005 |
And to get rid of a whole database, use DROP DATABASE: | %sql DROP DATABASE week3demo;
%sql SHOW DATABASES; | lectures/week-03/sql-demo.ipynb | dchud/warehousing-course | cc0-1.0 | a663de5e253350b24f910b1c306096ec |
We can use gradient descent to minimize a cost function, thereby optimizing our weights.
ANNs in Sklearn
Multi-layer Perceptron (MLP) models in sklearn
The advantages of MLP are:
- Capability to learn non-linear models.
- Capability to learn models in real-time (on-line learning) using partial_fit.
The disadvantages of MLP include:
- MLP with hidden layers have a non-convex loss function where there exists more than one local minimum. Therefore different random weight initializations can lead to different validation accuracy.
- MLP requires tuning a number of hyperparameters such as the number of hidden neurons, layers, and iterations.
- MLP is sensitive to feature scaling. | # build simple neural net with sklearn: An "OR" gate
from sklearn.neural_network import MLPClassifier
X = [[0., 0.], [1., 1.], [1., 0.], [0., 1.]]
y = [0, 1, 1, 1]
clf = MLPClassifier(hidden_layer_sizes=(5,2),
solver='lbfgs',
random_state=42)
clf.fit(X,y)
# predict new observations
clf.predict([[0,1]])
# find parameters
print([coef.shape for coef in clf.coefs_])
clf.coefs_
clf.predict([[2,2]])
clf.predict([[-2,2]])
clf.predict([[-2,-2]]) | Projects/Project5/NeuralNetSum.ipynb | ptpro3/ptpro3.github.io | mit | 960e028ef77ee340056533b684aa5259 |
Question 4
Write a function to update the dataframe to include a new column called "Points" which is a weighted value where each gold medal counts for 3 points, silver medals for 2 points, and bronze mdeals for 1 point. The function should return only the column (a Series object) which you created.
This function should return a Series named Points of length 146 | def answer_four():
return "YOUR ANSWER HERE" | intro-python-data-science/course1_downloads/Assignment 2.ipynb | joaoandre/algorithms | mit | 670aa9bbd9d4d91dfcf32090ef81cf87 |
Question 6
Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)?
This function should return a list of string values. | def answer_six():
return "YOUR ANSWER HERE" | intro-python-data-science/course1_downloads/Assignment 2.ipynb | joaoandre/algorithms | mit | ac727d489e58d17a4f96a683d1881b62 |
Construction de la dataframe et rΓ©alisation des graphiques | simulated_variables = ['coicop12_{}'.format(coicop12_index) for coicop12_index in range(1, 13)]
for year in [2000, 2005, 2011]:
survey_scenario = SurveyScenario.create(year = year)
pivot_table = pandas.DataFrame()
for values in simulated_variables:
pivot_table = pandas.concat([
pivot_table,
survey_scenario.compute_pivot_table(values = [values], columns = ['niveau_vie_decile'])
])
df = pivot_table.T
df['depenses_tot'] = df[['coicop12_{}'.format(i) for i in range(1, 13)]].sum(axis = 1)
for i in range(1, 13):
df['part_coicop12_{}'.format(i)] = \
df['coicop12_{}'.format(i)] / df['depenses_tot']
print 'Profil de la consommation des mΓ©nages en {}'.format(year)
graph_builder_bar(df[['part_coicop12_{}'.format(i) for i in range(1, 13)]])
| openfisca_france_indirect_taxation/examples/notebooks/consommations_coicop_par_decile.ipynb | openfisca/openfisca-france-indirect-taxation | agpl-3.0 | 94cd996ac00a532c7059e7949de78d83 |
νμ₯ μ ν
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/guide/extension_type"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.orgμμ 보기</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ko/guide/extension_type.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colabμμ μ€ν</a></td>
<td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ko/guide/extension_type.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHubμμ μμ€ λ³΄κΈ°</a></td>
<td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ko/guide/extension_type.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">λ
ΈνΈλΆ λ€μ΄λ‘λ</a></td>
</table>
μ€μ | !pip install -q tf_nightly
import tensorflow as tf
import numpy as np
from typing import Tuple, List, Mapping, Union, Optional
import tempfile | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | a0e7b5a82c3cd3bd3ae8992b96c26fa6 |
νμ₯ μ ν
μ¬μ©μ μ μ μ νμ μ¬μ©νλ©΄ νλ‘μ νΈλ₯Ό λ μ½κΈ° μ½κ³ λͺ¨λμμΌλ‘ μ μ§ κ΄λ¦¬ν μ μμ΅λλ€. κ·Έλ¬λ λλΆλΆμ TensorFlow APIλ μ¬μ©μ μ μ Python μ νμ λν μ§μμ΄ λ§€μ° μ νμ μ
λλ€. μ΄κ²μ (μ λͺ¨λ λμ μμ€μ APIλ₯Ό ν¬ν¨ Keras , tf.function , tf.SavedModel (μλ‘μ νμ λ 벨μ API) tf.while_loop λ° tf.concat ). TensorFlow νμ₯ μ ν μ μ¬μ©νμ¬ TensorFlowμ APIμ μννκ² μλνλ μ¬μ©μ μ μ κ°μ²΄ μ§ν₯ μ νμ μμ±ν μ μμ΅λλ€. tf.experimental.ExtensionType μ κΈ°λ³ΈμΌλ‘ νλ Python ν΄λμ€λ₯Ό μ μνκ³ μ ν μ£Όμ μ μ¬μ©νμ¬ κ° νλμ μ νμ μ§μ νλ©΄ λ©λλ€. | class TensorGraph(tf.experimental.ExtensionType):
"""A collection of labeled nodes connected by weighted edges."""
edge_weights: tf.Tensor # shape=[num_nodes, num_nodes]
node_labels: Mapping[str, tf.Tensor] # shape=[num_nodes]; dtype=any
class MaskedTensor(tf.experimental.ExtensionType):
"""A tensor paired with a boolean mask, indicating which values are valid."""
values: tf.Tensor
mask: tf.Tensor # shape=values.shape; false for missing/invalid values.
class CSRSparseMatrix(tf.experimental.ExtensionType):
"""Compressed sparse row matrix (https://en.wikipedia.org/wiki/Sparse_matrix)."""
values: tf.Tensor # shape=[num_nonzero]; dtype=any
col_index: tf.Tensor # shape=[num_nonzero]; dtype=int64
row_index: tf.Tensor # shape=[num_rows+1]; dtype=int64 | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6b25cce00c7eb8b5ecdaa056199448f2 |
tf.experimental.ExtensionType κΈ°λ³Έ ν΄λμ€λ νμ€ Python λΌμ΄λΈλ¬λ¦¬μ typing.NamedTuple λ° @dataclasses.dataclass μ μ μ¬νκ² μλν©λλ€. νΉν νλ μ ν μ£Όμμ κΈ°λ°μΌλ‘ μμ±μμ νΉμ λ©μλ(μ: __repr__ λ° __eq__
μΌλ°μ μΌλ‘ νμ₯ μ νμ λ€μ λ κ°μ§ λ²μ£Ό μ€ νλλ‘ λΆλ₯λλ κ²½ν₯μ΄ μμ΅λλ€.
κ΄λ ¨ κ°μ 컬λ μ
μ κ·Έλ£Ήννκ³ ν΄λΉ κ°μ κΈ°λ°μΌλ‘ μ μ©ν μμ
μ μ 곡ν μ μλ λ°μ΄ν° ꡬ쑰. λ°μ΄ν° ꡬ쑰λ μλΉν μΌλ°μ μΌ μ μμ΅λλ€(μ TensorGraph μ). λλ νΉμ λͺ¨λΈμ κ³ λλ‘ λ§μΆ€νλ μ μμ΅λλ€.
"Tensor"μ κ°λ
μ μ λ¬Έννκ±°λ νμ₯νλ Tensorμ μ μ¬ν μ νμ
λλ€. μ΄ λ²μ£Όμ μ νμλ rank , shape λ° μΌλ°μ μΌλ‘ dtype . tf.stack , tf.add λλ tf.matmul )κ³Ό ν¨κ» μ¬μ©νλ κ²μ΄ μ’μ΅λλ€. MaskedTensor λ° CSRSparseMatrix λ ν
μ μ μ¬ μ νμ μμ
λλ€.
μ§μλλ API
νμ₯ μ νμ λ€μ TensorFlow APIμμ μ§μλ©λλ€.
Keras Models λ° Layers λν μ
λ ₯ λ° μΆλ ₯μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
tf.data.Dataset : νμ₯ μ νμ Datasets Iterators μν΄ λ°νλ©λλ€.
Tensorflow νλΈ tf.hub λͺ¨λμ μ
λ ₯ λ° μΆλ ₯μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
SavedModel SavedModel ν¨μμ λν μ
λ ₯ λ° μΆλ ₯μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
tf.function @tf.function λ°μ½λ μ΄ν°λ‘ λνλ ν¨μμ μΈμ λ° λ°ν κ°μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
while 루ν : νμ₯ μ νμ tf.while_loop μμ 루ν λ³μλ‘ μ¬μ©ν μ μμΌλ©° while 루ν λ³Έλ¬Έμ λν μΈμ λ° λ°ν κ°μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
conditionals tf.cond λ° tf.case μ¬μ©νμ¬ μ‘°κ±΄λΆλ‘ μ νν μ μμ΅λλ€.
py_function : νμ₯ μ νμ μΈμλ‘ μ¬μ©ν μ μκ³ func μΈμμ tf.py_function λ°νν μ μμ΅λλ€.
Tensor ops tf.matmul , tf.gather λ° tf.reduce_sum )μ νμ©νλ λλΆλΆμ TensorFlow μμ
μ μ§μνλλ‘ νμ₯λ μ μμ΅λλ€. μμΈν λ΄μ©μ μλμ " λμ€ν¨μΉ " μΉμ
μ μ°Έμ‘°νμμμ€.
λ°°ν¬ μ λ΅ : νμ₯ μ νμ 볡μ λ³ΈλΉ κ°μΌλ‘ μ¬μ©ν μ μμ΅λλ€.
μμΈν λ΄μ©μ μλ "ExtensionTypesλ₯Ό μ§μνλ TensorFlow API" μΉμ
μ μ°Έμ‘°νμΈμ.
μꡬ μ¬ν
νλ μ ν
λͺ¨λ νλ(μΌλͺ
μΈμ€ν΄μ€ λ³μ)λ₯Ό μ μΈν΄μΌ νλ©° κ° νλμ μ ν μ£Όμμ μ 곡ν΄μΌ ν©λλ€. λ€μ μ ν μ£Όμμ΄ μ§μλ©λλ€.
μ ν | μμ
--- | ---
νμ΄μ¬ μ μ | i: int
νμ΄μ¬ μλ | f: float
νμ΄μ¬ λ¬Έμμ΄ | s: str
νμ΄μ¬ λΆμΈ | b: bool
νμ΄μ¬ μμ | n: None
ν
μ λͺ¨μ | shape: tf.TensorShape
ν
μ dtypes | dtype: tf.DType
ν
μ | t: tf.Tensor
νμ₯ μ ν | mt: MyMaskedTensor
λΉμ ν ν
μ | rt: tf.RaggedTensor
ν¬μ ν
μ | st: tf.SparseTensor
μΈλ±μ±λ μ¬λΌμ΄μ€ | s: tf.IndexedSlices
μ νμ ν
μ | o: tf.experimental.Optional
μ ν μ‘°ν© | int_or_float: typing.Union[int, float]
νν | params: typing.Tuple[int, float, tf.Tensor, int]
κ°λ³ κΈΈμ΄ νν | lengths: typing.Tuple[int, ...]
맀ν | tags: typing.Mapping[str, tf.Tensor]
μ νμ κ° | weight: typing.Optional[tf.Tensor]
κ°λ³μ±
νμ₯ μ νμ λ³κ²½ λΆκ°λ₯ν΄μΌ ν©λλ€. μ΄λ κ² νλ©΄ TensorFlowμ κ·Έλν μΆμ λ©μ»€λμ¦μΌλ‘ μ μ νκ² μΆμ ν μ μμ΅λλ€. νμ₯ μ ν κ°μ λ³κ²½νλ €λ κ²½μ° κ°μ λ³ννλ λ©μλλ₯Ό λμ μ μνλ κ²μ΄ μ’μ΅λλ€. μλ₯Ό λ€μ΄ MaskedTensor λ₯Ό λ³κ²½νκΈ° μν΄ set_mask MaskedTensor λ₯Ό λ°ννλ replace_mask λ©μλλ₯Ό μ μν μ μμ΅λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
def replace_mask(self, new_mask):
self.values.shape.assert_is_compatible_with(new_mask.shape)
return MaskedTensor(self.values, new_mask) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | cb3a8bc3a0c4ceebdeb9156fc79a0b3b |
ExtensionType μΆκ°ν κΈ°λ₯
ExtensionType κΈ°λ³Έ ν΄λμ€λ λ€μ κΈ°λ₯μ μ 곡ν©λλ€.
μμ±μ( __init__ ).
μΈμ κ°λ₯ν νν λ°©λ²( __repr__ ).
λ±μ λ° λΆλ±μ μ°μ°μ( __eq__ ).
μ ν¨μ± κ²μ¬ λ°©λ²( __validate__ ).
κ°μ λΆλ³μ±.
μ€μ²©λ TypeSpec .
ν
μ API λμ€ν¨μΉ μ§μ.
μ΄ κΈ°λ₯μ μ¬μ©μ μ μνλ λ°©λ²μ λν μμΈν λ΄μ©μ μλμ "ExtensionType μ¬μ©μ μ μ" μΉμ
μ μ°Έμ‘°νμμμ€.
건μ€μ
ExtensionType μ μν΄ μΆκ°λ μμ±μλ κ° νλλ₯Ό λͺ
λͺ
λ μΈμλ‘ μ¬μ©ν©λλ€(ν΄λμ€ μ μμ λμ΄λ μμλλ‘). μ΄ μμ±μλ κ° λ§€κ°λ³μλ₯Ό μ ν κ²μ¬νκ³ νμν κ²½μ° λ³νν©λλ€. νΉν, Tensor tf.convert_to_tensor μ¬μ©νμ¬ λ³νλ©λλ€. Tuple νλλ‘ λ³νλ©λλ€ tuple μ; Mapping νλλ λ³κ²½ν μ μλ μ¬μ μΌλ‘ λ³νλ©λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
# Constructor takes one parameter for each field.
mt = MaskedTensor(values=[[1, 2, 3], [4, 5, 6]],
mask=[[True, True, False], [True, False, True]])
# Fields are type-checked and converted to the declared types.
# E.g., mt.values is converted to a Tensor.
print(mt.values) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 9ea3cadada933962a4aca15a33f33926 |
νλ κ°μ μ μΈλ μ νμΌλ‘ λ³νν μ μλ κ²½μ° μμ±μλ TypeError | try:
MaskedTensor([1, 2, 3], None)
except TypeError as e:
print(f"Got expected TypeError: {e}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 62f282d7d7a885aea66a30f0871929a9 |
νλμ κΈ°λ³Έκ°μ ν΄λμ€ μμ€μμ κ°μ μ€μ νμ¬ μ§μ ν μ μμ΅λλ€. | class Pencil(tf.experimental.ExtensionType):
color: str = "black"
has_erasor: bool = True
length: tf.Tensor = 1.0
Pencil()
Pencil(length=0.5, color="blue") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 882e69eddb6eabdcbc176639e0e8c874 |
μΈμ κ°λ₯ν νν
ExtensionType μ ν΄λμ€ μ΄λ¦κ³Ό κ° νλμ κ°μ ν¬ν¨νλ κΈ°λ³Έ μΈμ κ°λ₯ν νν λ°©λ²( __repr__ | print(MaskedTensor(values=[1, 2, 3], mask=[True, True, False])) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | b40e0f92426eee71c5188ed4790a4c30 |
λ±νΈ μ°μ°μ
ExtensionType μ μ νμ΄ λμΌνκ³ λͺ¨λ νλκ° λμΌν κ²½μ° λ κ°μ λμΌνκ² κ°μ£Όνλ κΈ°λ³Έ λλ± μ°μ°μ( __eq__ λ° __ne__ ν
μ νλλ λͺ¨μμ΄ λμΌνκ³ λͺ¨λ μμμ λν΄ μμλ³λ‘ λμΌν κ²½μ° λμΌν κ²μΌλ‘ κ°μ£Όλ©λλ€. | a = MaskedTensor([1, 2], [True, False])
b = MaskedTensor([[3, 4], [5, 6]], [[False, True], [True, True]])
print(f"a == a: {a==a}")
print(f"a == b: {a==b}")
print(f"a == a.values: {a==a.values}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 3657bd656ca423337087c46e42ad36e5 |
μ°Έκ³ : Tensor κ° ν¬ν¨λ κ²½μ° __eq__ λ (Python λΆμΈ κ° λμ ) Tensor λ°νν μ μμ΅λλ€.
κ²μ¦ λ°©λ²
ExtensionType μ νλμ λν μ ν¨μ± κ²μ¬λ₯Ό μννκΈ° μν΄ μ¬μ μν μ μλ __validate__ μμ±μκ° νΈμΆλκ³ νλκ° μ ν κ²μ¬λκ³ μ μΈλ μ νμΌλ‘ λ³νλ νμ μ€νλλ―λ‘ λͺ¨λ νλμ μ μΈλ μ νμ΄ μλ€κ³ κ°μ ν μ μμ΅λλ€.
λ€μ μμ λ MaskedTensor λ₯Ό μ
λ°μ΄νΈνμ¬ ν΄λΉ νλμ shape s λ° dtype μ νμΈν©λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
"""A tensor paired with a boolean mask, indicating which values are valid."""
values: tf.Tensor
mask: tf.Tensor
def __validate__(self):
self.values.shape.assert_is_compatible_with(self.mask.shape)
assert self.mask.dtype.is_bool, 'mask.dtype must be bool'
try:
MaskedTensor([1, 2, 3], [0, 1, 0]) # wrong dtype for mask.
except AssertionError as e:
print(f"Got expected AssertionError: {e}")
try:
MaskedTensor([1, 2, 3], [True, False]) # shapes don't match.
except ValueError as e:
print(f"Got expected ValueError: {e}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 2fd7173dd86fadf96e427f2f2756801d |
κ°μ λΆλ³μ±
ExtensionType __setattr__ λ° __delattr__ λ©μλλ₯Ό μ¬μ μνμ¬ λ³νμ λ°©μ§νμ¬ νμ₯ μ ν κ°μ λ³κ²½ν μ μλλ‘ ν©λλ€. | mt = MaskedTensor([1, 2, 3], [True, False, True])
try:
mt.mask = [True, True, True]
except AttributeError as e:
print(f"Got expected AttributeError: {e}")
try:
mt.mask[0] = False
except TypeError as e:
print(f"Got expected TypeError: {e}")
try:
del mt.mask
except AttributeError as e:
print(f"Got expected AttributeError: {e}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6d782ad3ff38c9987e9482f0999488d2 |
μ€μ²©λ μ ν μ¬μ
κ° ExtensionType ν΄λμ€μλ μλμΌλ‘ μμ±λκ³ <extension_type_name>.Spec TypeSpec ν΄λμ€κ° μμ΅λλ€.
μ΄ ν΄λμ€λ μ€μ²©λ ν
μμ κ°μ μ μΈν κ°μμ λͺ¨λ μ 보λ₯Ό μΊ‘μ²ν©λλ€. νΉν TypeSpec μ μ€μ²©λ Tensor, ExtensionType λλ CompositeTensorλ₯Ό TypeSpec μΌλ‘ λ체νμ¬ μμ±λ©λλ€. | class Player(tf.experimental.ExtensionType):
name: tf.Tensor
attributes: Mapping[str, tf.Tensor]
anne = Player("Anne", {"height": 8.3, "speed": 28.1})
anne_spec = tf.type_spec_from_value(anne)
print(anne_spec.name) # Records dtype and shape, but not the string value.
print(anne_spec.attributes) # Records keys and TensorSpecs for values. | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 094cf538674bf22d72056319d3ca791f |
TypeSpec κ°μ λͺ
μμ μΌλ‘ ꡬμ±νκ±°λ tf.type_spec_from_value μ¬μ©νμ¬ ExtensionType κ°μμ λΉλν μ μμ΅λλ€. | spec1 = Player.Spec(name=tf.TensorSpec([], tf.float32), attributes={})
spec2 = tf.type_spec_from_value(anne) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | fc5b147bffe0c440efab23c5b4546295 |
TypeSpec μ TensorFlowμμ κ°μ μ μ κ΅¬μ± μμ μ λμ κ΅¬μ± μμλ‘ λλλ λ° μ¬μ©λ©λλ€.
κ·Έλν μμ± μ κ³ μ λλ μ μ κ΅¬μ± μμ tf.TypeSpec μΈμ½λ©λ©λλ€.
κ·Έλνκ° μ€νλ λλ§λ€ λ€λ₯Ό μ μλ λμ κ΅¬μ± μμ tf.Tensor λͺ©λ‘μΌλ‘ μΈμ½λ©λ©λλ€.
μλ₯Ό λ€μ΄, tf.functionμ μΈμμ μ΄μ μ λ³Ό μ μλ TypeSpec tf.function . | @tf.function
def anonymize_player(player):
print("<<TRACING>>")
return Player("<anonymous>", player.attributes)
# Function gets traced (first time the function has been called):
anonymize_player(Player("Anne", {"height": 8.3, "speed": 28.1}))
# Function does NOT get traced (same TypeSpec: just tensor values changed)
anonymize_player(Player("Bart", {"height": 8.1, "speed": 25.3}))
# Function gets traced (new TypeSpec: keys for attributes changed):
anonymize_player(Player("Chuck", {"height": 11.0, "jump": 5.3})) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6b9fbef3eddbcd5f667fa81aeab466f6 |
μμΈν λ΄μ©μ tf.function κ°μ΄λλ₯Ό μ°Έμ‘°νμμμ€.
ExtensionType μ¬μ©μ μ μ
λ¨μν νλμ ν΄λΉ μ νμ μ μΈνλ κ² μΈμλ νμ₯ μ νμ λ€μμ μνν μ μμ΅λλ€.
κΈ°λ³Έ μΈμ κ°λ₯ν νν( __repr__ )μ μ¬μ μν©λλ€.
λ°©λ²μ μ μν©λλ€.
ν΄λμ€ λ©μλμ μ μ λ©μλλ₯Ό μ μν©λλ€.
μμ±μ μ μν©λλ€.
κΈ°λ³Έ μμ±μ( __init__ )λ₯Ό μ¬μ μν©λλ€.
κΈ°λ³Έ νλ± μ°μ°μ( __eq__ )λ₯Ό μ¬μ μν©λλ€.
μ°μ°μλ₯Ό μ μν©λλ€(μ: __add__ λ° __lt__ ).
νλμ κΈ°λ³Έκ°μ μ μΈν©λλ€.
νμ ν΄λμ€λ₯Ό μ μν©λλ€.
κΈ°λ³Έ μΈμ κ°λ₯ν νν μ¬μ μ
νμ₯ μ νμ λν΄ μ΄ κΈ°λ³Έ λ¬Έμμ΄ λ³ν μ°μ°μλ₯Ό μ¬μ μν μ μμ΅λλ€. λ€μ μμ μμλ κ°μ΄ Eager λͺ¨λμμ μΈμλ λ λ μ½κΈ° μ¬μ΄ λ¬Έμμ΄ ννμ μμ± MaskedTensor | class MaskedTensor(tf.experimental.ExtensionType):
"""A tensor paired with a boolean mask, indicating which values are valid."""
values: tf.Tensor
mask: tf.Tensor # shape=values.shape; false for invalid values.
def __repr__(self):
return masked_tensor_str(self.values, self.mask)
def masked_tensor_str(values, mask):
if isinstance(values, tf.Tensor):
if hasattr(values, 'numpy') and hasattr(mask, 'numpy'):
return f'<MaskedTensor {masked_tensor_str(values.numpy(), mask.numpy())}>'
else:
return f'MaskedTensor(values={values}, mask={mask})'
if len(values.shape) == 1:
items = [repr(v) if m else '_' for (v, m) in zip(values, mask)]
else:
items = [masked_tensor_str(v, m) for (v, m) in zip(values, mask)]
return '[%s]' % ', '.join(items)
mt = MaskedTensor(values=[[1, 2, 3], [4, 5, 6]],
mask=[[True, True, False], [True, False, True]])
print(mt) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 39f7827f01b937956b2f4a747a039647 |
λ©μλ μ μ
νμ₯ μ νμ μΌλ° Python ν΄λμ€μ λ§μ°¬κ°μ§λ‘ λ©μλλ₯Ό μ μν μ μμ΅λλ€. μλ₯Ό λ€μ΄ MaskedTensor default λ체λ λ§μ€νΉλ κ° self μ 볡μ¬λ³Έμ λ°ννλ with_default λ©μλλ₯Ό μ μν μ μμ΅λλ€. @tf.function λ°μ½λ μ΄ν°λ‘ μ£Όμμ λ¬ μ μμ΅λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
def with_default(self, default):
return tf.where(self.mask, self.values, default)
MaskedTensor([1, 2, 3], [True, False, True]).with_default(0) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | f602c9035325db46fc507d1b7c10e507 |
ν΄λμ€ λ©μλ λ° μ μ λ©μλ μ μ
@classmethod λ° @staticmethod λ°μ½λ μ΄ν°λ₯Ό μ¬μ©νμ¬ λ©μλλ₯Ό μ μν μ μμ΅λλ€. μλ₯Ό λ€μ΄ MaskedTensor μ νμ μ£Όμ΄μ§ κ°μΌλ‘ λͺ¨λ μμλ₯Ό λ§μ€νΉνλ ν©ν 리 λ©μλλ₯Ό μ μν μ μμ΅λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
def __repr__(self):
return masked_tensor_str(self.values, self.mask)
@staticmethod
def from_tensor_and_value_to_mask(values, value_to_mask):
return MaskedTensor(values, values == value_to_mask)
x = tf.constant([[1, 0, 2], [3, 0, 0]])
MaskedTensor.from_tensor_and_value_to_mask(x, 0) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 3ddbba144651725495c2ae81dc0d118e |
μμ± μ μ
νμ₯ μ νμ μΌλ° Python ν΄λμ€μ λ§μ°¬κ°μ§λ‘ @property λ°μ½λ μ΄ν°λ₯Ό μ¬μ©νμ¬ μμ±μ μ μν μ μμ΅λλ€. μλ₯Ό λ€μ΄ MaskedTensor μ νμ κ°μ dtypeμ λν μ½μΉμΈ dtype μμ±μ μ μν μ μμ΅λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
@property
def dtype(self):
return self.values.dtype
MaskedTensor([1, 2, 3], [True, False, True]).dtype | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | a363cc69b424c1cf43324a6037fa2348 |
κΈ°λ³Έ μμ±μ μ¬μ μ
νμ₯ μ νμ λν κΈ°λ³Έ μμ±μλ₯Ό μ¬μ μν μ μμ΅λλ€. μ¬μ©μ μ μ μμ±μλ μ μΈλ λͺ¨λ νλμ λν΄ κ°μ μ€μ ν΄μΌ ν©λλ€. μ¬μ©μ μ μ μμ±μκ° λ°νλ ν λͺ¨λ νλκ° μ ν κ²μ¬λκ³ μμμ μ€λͺ
ν λλ‘ κ°μ΄ λ³νλ©λλ€. | class Toy(tf.experimental.ExtensionType):
name: str
price: tf.Tensor
def __init__(self, name, price, discount=0):
self.name = name
self.price = price * (1 - discount)
print(Toy("ball", 5.0, discount=0.2)) # On sale -- 20% off! | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 0dbaae94605a6e6e9e2cf185c1fcdf24 |
λλ κΈ°λ³Έ μμ±μλ₯Ό κ·Έλλ‘ λκ³ νλ μ΄μμ ν©ν 리 λ©μλλ₯Ό μΆκ°νλ κ²μ κ³ λ €ν μ μμ΅λλ€. μ: | class Toy(tf.experimental.ExtensionType):
name: str
price: tf.Tensor
@staticmethod
def new_toy_with_discount(name, price, discount):
return Toy(name, price * (1 - discount))
print(Toy.new_toy_with_discount("ball", 5.0, discount=0.2)) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 3240e7a4a42d5a6170bce30093892028 |
κΈ°λ³Έ νλ± μ°μ°μ μ¬μ μ( __eq__ )
νμ₯ μ νμ λν __eq__ μ°μ°μλ₯Ό μ¬μ μν μ μμ΅λλ€. λ€μ μμ μμλ MaskedTensor λΉκ΅ν λ λ§μ€ν¬λ μμλ₯Ό 무μνλλ‘ MaskedTensorλ₯Ό μ
λ°μ΄νΈν©λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
def __repr__(self):
return masked_tensor_str(self.values, self.mask)
def __eq__(self, other):
result = tf.math.equal(self.values, other.values)
result = result | ~(self.mask & other.mask)
return tf.reduce_all(result)
x = MaskedTensor([1, 2, 3, 4], [True, True, False, True])
y = MaskedTensor([5, 2, 0, 4], [False, True, False, True])
print(x == y) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 12804ecc225a4527e4d50daf0202f4ef |
μ°Έκ³ : κΈ°λ³Έ ꡬνμ λ¨μν __eq__ λ₯Ό νΈμΆνκ³ κ²°κ³Όλ₯Ό 무ν¨ννκΈ° __ne__ λ₯Ό μ¬μ μν νμκ° μμ΅λλ€.
μ λ°©ν₯ μ°Έμ‘° μ¬μ©
νλ μ νμ΄ μμ§ μ μλμ§ μμ κ²½μ° μ ν μ΄λ¦μ΄ ν¬ν¨λ λ¬Έμμ΄μ λμ μ¬μ©ν μ μμ΅λλ€. λ€μ μμ μμλ Node μ νμ΄ μμ§ (μμ ν) μ μλμ§ μμκΈ° λλ¬Έμ "Node" children νλμ μ£Όμμ λ€λ λ° μ¬μ©λ©λλ€. | class Node(tf.experimental.ExtensionType):
value: tf.Tensor
children: Tuple["Node", ...] = ()
Node(3, [Node(5), Node(2)]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | cb681a320cede6912e473abd324a224f |
μλΈν΄λμ€ μ μ
νμ₯ μ νμ νμ€ Python ꡬ문μ μ¬μ©νμ¬ νμ λΆλ₯λ μ μμ΅λλ€. νμ₯ μ ν νμ ν΄λμ€λ μ νλ, λ©μλ λ° μμ±μ μΆκ°ν μ μμ΅λλ€. μμ±μ, μΈμ κ°λ₯ν νν λ° λ±νΈ μ°μ°μλ₯Ό μ¬μ μν μ μμ΅λλ€. λ€μ μμ λ μΈ κ°μ Tensor νλλ₯Ό μ¬μ©νμ¬ λ
Έλ μ¬μ΄μ κ°μ₯μ리 μ§ν©μ μΈμ½λ©νλ TensorGraph κ·Έλ° λ€μ κ° λ
Έλμ λν "κΈ°λ₯ κ°"μ κΈ°λ‘νκΈ° μν΄ Tensor νλλ₯Ό μΆκ°νλ νμ ν΄λμ€λ₯Ό μ μν©λλ€. λν νμ ν΄λμ€λ κ°μ₯μ리λ₯Ό λ°λΌ νΉμ± κ°μ μ ννλ λ°©λ²μ μ μν©λλ€. | class TensorGraph(tf.experimental.ExtensionType):
num_nodes: tf.Tensor
edge_src: tf.Tensor # edge_src[e] = index of src node for edge e.
edge_dst: tf.Tensor # edge_dst[e] = index of dst node for edge e.
class TensorGraphWithNodeFeature(TensorGraph):
node_features: tf.Tensor # node_features[n] = feature value for node n.
def propagate_features(self, weight=1.0) -> 'TensorGraphWithNodeFeature':
updates = tf.gather(self.node_features, self.edge_src) * weight
new_node_features = tf.tensor_scatter_nd_add(
self.node_features, tf.expand_dims(self.edge_dst, 1), updates)
return TensorGraphWithNodeFeature(
self.num_nodes, self.edge_src, self.edge_dst, new_node_features)
g = TensorGraphWithNodeFeature( # Edges: 0->1, 4->3, 2->2, 2->1
num_nodes=5, edge_src=[0, 4, 2, 2], edge_dst=[1, 3, 2, 1],
node_features=[10.0, 0.0, 2.0, 5.0, -1.0, 0.0])
print("Original features:", g.node_features)
print("After propagating:", g.propagate_features().node_features) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | b5fae141c11137008416f645e1f9ac80 |
κ°μΈ νλ μ μ
νμ₯ μ νμ νλλ μ λμ¬μ λ°μ€μ λΆμ¬ λΉκ³΅κ°λ‘ νμν μ μμ΅λλ€(νμ€ Python κ·μΉμ λ°λΌ). μ΄κ²μ TensorFlowκ° μ΄λ€ μμΌλ‘λ νλλ₯Ό μ²λ¦¬νλ λ°©μμ μν₯μ λ―ΈμΉμ§ μμ΅λλ€. κ·Έλ¬λ λ¨μν νμ₯ μ νμ λͺ¨λ μ¬μ©μμκ² ν΄λΉ νλκ° λΉκ³΅κ°λΌλ μ νΈ μν μ ν©λλ€.
ExtensionTypeμ TypeSpec
κ° ExtensionType ν΄λμ€μλ μλμΌλ‘ μμ±λκ³ <extension_type_name>.Spec TypeSpec ν΄λμ€κ° μμ΅λλ€. μμΈν λ΄μ©μ μμ "μ€μ²©λ TypeSpec" μΉμ
μ μ°Έμ‘°νμΈμ.
TypeSpec μ μ¬μ©μ μ μνλ €λ©΄ Spec μ΄λΌλ μ체 μ€μ²© ν΄λμ€λ₯Ό μ μνκΈ°λ§ νλ©΄ ExtensionType μ΄ μ΄λ₯Ό μλμΌλ‘ μμ±λ TypeSpec μ κΈ°μ΄λ‘ μ¬μ©ν©λλ€. Spec ν΄λμ€λ₯Ό μ¬μ©μ μ μν μ μμ΅λλ€.
κΈ°λ³Έ μΈμ κ°λ₯ν ννμ μ¬μ μν©λλ€.
κΈ°λ³Έ μμ±μλ₯Ό μ¬μ μν©λλ€.
λ©μλ, ν΄λμ€ λ©μλ, μ μ λ©μλ λ° μμ±μ μ μν©λλ€.
λ€μ μμ μμλ μ¬μ©νκΈ° μ½λλ‘ MaskedTensor.Spec ν΄λμ€λ₯Ό μ¬μ©μ μ§μ ν©λλ€. | class MaskedTensor(tf.experimental.ExtensionType):
values: tf.Tensor
mask: tf.Tensor
shape = property(lambda self: self.values.shape)
dtype = property(lambda self: self.values.dtype)
def __repr__(self):
return masked_tensor_str(self.values, self.mask)
def with_values(self, new_values):
return MaskedTensor(new_values, self.mask)
class Spec:
def __init__(self, shape, dtype=tf.float32):
self.values = tf.TensorSpec(shape, dtype)
self.mask = tf.TensorSpec(shape, tf.bool)
def __repr__(self):
return f"MaskedTensor.Spec(shape={self.shape}, dtype={self.dtype})"
shape = property(lambda self: self.values.shape)
dtype = property(lambda self: self.values.dtype) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 3730bc723d46fd4157f5d18150c5b7ed |
μ°Έκ³ : μ¬μ©μ μ μ Spec ExtensionType μ μΈλμ§ μμ μΈμ€ν΄μ€ λ³μλ₯Ό μ¬μ©ν μ μμ΅λλ€.
ν
μ API λμ€ν¨μΉ
tf.Tensor μ νμ μν΄ μ μλ μΈν°νμ΄μ€λ₯Ό μ λ¬Έννκ±°λ νμ₯νλ€λ μ μμ "ν
μμ μ μ¬"ν μ μμ΅λλ€. ν
μμ μ μ¬ν νμ₯ μ νμ μλ‘λ RaggedTensor , SparseTensor λ° MaskedTensor μμ΅λλ€. λμ€ν¨μΉ λ°μ½λ μ΄ν° λ ν
μμ μ μ¬ν νμ₯ μ νμ μ μ©λ λ TensorFlow μμ
μ κΈ°λ³Έ λμμ μ¬μ μνλ λ° μ¬μ©ν μ μμ΅λλ€. TensorFlowλ νμ¬ μΈ κ°μ§ λμ€ν¨μΉ λ°μ½λ μ΄ν°λ₯Ό μ μν©λλ€.
@tf.experimental.dispatch_for_api(tf_api)
@tf.experimental.dispatch_for_unary_elementwise_api(x_type)
@tf.experimental.dispatch_for_binary_elementwise_apis(x_type, y_type)
λ¨μΌ APIμ λν λμ€ν¨μΉ
tf.experimental.dispatch_for_api λ°μ½λ μ΄ν°λ μ§μ λ μλͺ
μΌλ‘ νΈμΆλ λ μ§μ λ TensorFlow μμ
μ κΈ°λ³Έ λμμ μ¬μ μν©λλ€. μλ₯Ό λ€μ΄ μ΄ λ°μ½λ μ΄ν°λ₯Ό μ¬μ©νμ¬ tf.stack μ΄ MaskedTensor κ°μ μ²λ¦¬νλ λ°©λ²μ μ§μ ν μ μμ΅λλ€. | @tf.experimental.dispatch_for_api(tf.stack)
def masked_stack(values: List[MaskedTensor], axis = 0):
return MaskedTensor(tf.stack([v.values for v in values], axis),
tf.stack([v.mask for v in values], axis)) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 64de0acfd306952c47b636a792d4f524 |
MaskedTensor κ° λͺ©λ‘κ³Ό ν¨κ» νΈμΆλ λλ§λ€ tf.stack λν κΈ°λ³Έ ꡬνμ μ¬μ μ values typing.List[MaskedTensor] μ£ΌμμΌλ‘ μ§μ λμ΄ μκΈ° λλ¬Έμ
λλ€): | x = MaskedTensor([1, 2, 3], [True, True, False])
y = MaskedTensor([4, 5, 6], [False, True, True])
tf.stack([x, y]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | dcafafb56a3e02388d6b31254078abd6 |
tf.stack μ΄ νΌν©λ MaskedTensor λ° Tensor κ° λͺ©λ‘μ μ²λ¦¬ν μ μλλ‘ νλ €λ©΄ values 맀κ°λ³μμ λν μ ν μ£Όμμ ꡬ체ννκ³ ν¨μ λ³Έλ¬Έμ μ μ νκ² μ
λ°μ΄νΈν μ μμ΅λλ€. | tf.experimental.unregister_dispatch_for(masked_stack)
def convert_to_masked_tensor(x):
if isinstance(x, MaskedTensor):
return x
else:
return MaskedTensor(x, tf.ones_like(x, tf.bool))
@tf.experimental.dispatch_for_api(tf.stack)
def masked_stack_v2(values: List[Union[MaskedTensor, tf.Tensor]], axis = 0):
values = [convert_to_masked_tensor(v) for v in values]
return MaskedTensor(tf.stack([v.values for v in values], axis),
tf.stack([v.mask for v in values], axis))
x = MaskedTensor([1, 2, 3], [True, True, False])
y = tf.constant([4, 5, 6])
tf.stack([x, y, x]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 353cd872d0bbc46ac9c6e2714c0c6894 |
μ¬μ μν μ μλ API λͺ©λ‘μ tf.experimental.dispatch_for_api λν API μ€λͺ
μλ₯Ό μ°Έμ‘°νμΈμ.
λͺ¨λ λ¨ν μμλ³ APIμ λν λμ€ν¨μΉ
tf.experimental.dispatch_for_unary_elementwise_apis λ°μ½λ μ΄ν°λ 첫 λ²μ§Έ μΈμ(μΌλ°μ μΌλ‘ μ΄λ¦μ΄ x )μ λν κ°μ΄ μ ν μ£Όμ x_type κ³Ό μΌμΉν λλ§λ€ λͺ¨λ λ¨ν μμλ³ μ°μ°(μ: tf.math.cos )μ κΈ°λ³Έ λμμ μ¬μ μν©λλ€. λ°μ½λ μ΄ν
λ ν¨μλ λ κ°μ μΈμλ₯Ό μ·¨ν΄μΌ ν©λλ€.
api_func : λ¨μΌ 맀κ°λ³μλ₯Ό μ·¨νκ³ μμλ³ μ°μ°μ μννλ ν¨μ(μ: tf.abs ).
x : μμλ³ μ°μ°μ 첫 λ²μ§Έ μΈμμ
λλ€.
MaskedTensor μ νμ μ²λ¦¬νκΈ° μν΄ λͺ¨λ λ¨ν μμλ³ μ°μ°μ μ
λ°μ΄νΈν©λλ€. | @tf.experimental.dispatch_for_unary_elementwise_apis(MaskedTensor)
def masked_tensor_unary_elementwise_api_handler(api_func, x):
return MaskedTensor(api_func(x.values), x.mask) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6111e366ca3e32b869af3c6a6d32e7fe |
MaskedTensor μμ λ¨ν μμλ³ μ°μ°μ΄ νΈμΆλ λλ§λ€ μ¬μ©λ©λλ€. | x = MaskedTensor([1, -2, -3], [True, False, True])
print(tf.abs(x))
print(tf.ones_like(x, dtype=tf.float32)) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | f0d76b9e5ea87bd5bf026e8bbe7624f8 |
λ°μ΄λ리 λͺ¨λ μμλ³ APIμ λν λμ€ν¨μΉ
λ§μ°¬κ°μ§λ‘ tf.experimental.dispatch_for_binary_elementwise_apis MaskedTensor μ νμ μ²λ¦¬νκΈ° μν΄ λͺ¨λ λ°μ΄λ리 μμλ³ μ°μ°μ μ
λ°μ΄νΈνλ λ° μ¬μ©ν μ μμ΅λλ€. | @tf.experimental.dispatch_for_binary_elementwise_apis(MaskedTensor, MaskedTensor)
def masked_tensor_binary_elementwise_api_handler(api_func, x, y):
return MaskedTensor(api_func(x.values, y.values), x.mask & y.mask)
x = MaskedTensor([1, -2, -3], [True, False, True])
y = MaskedTensor([[4], [5]], [[True], [False]])
tf.math.add(x, y) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | aa4f6b6316221929ee8ecdc6ef7675d8 |
μ¬μ μλλ μμλ³ API λͺ©λ‘μ tf.experimental.dispatch_for_unary_elementwise_apis λ° tf.experimental.dispatch_for_binary_elementwise_apis λν API λ¬Έμλ₯Ό μ°Έμ‘°νμΈμ.
μΌκ΄ μ²λ¦¬ κ°λ₯ν νμ₯ μ ν
ExtensionType λ¨μΌ μΈμ€ν΄μ€ κ°μ λ°°μΉλ₯Ό λνλ΄λ λ° μ¬μ©ν μμλ κ²½μ° batchableμ΄λ€. Tensor λ°°μΉ μ°¨μμ μΆκ°νμ¬ μνλ©λλ€. λ€μ TensorFlow APIλ₯Ό μ¬μ©νλ €λ©΄ λͺ¨λ νμ₯ μ ν μ
λ ₯μ΄ μΌκ΄ μ²λ¦¬ κ°λ₯ν΄μΌ ν©λλ€.
tf.data.Dataset ( batch , unbatch , from_tensor_slices )
tf.Keras ( fit , evaluate , predict )
tf.map_fn
κΈ°λ³Έμ μΌλ‘ BatchableExtensionType Tensor , CompositeTensor λ° ExtensionType μΌκ΄ μ²λ¦¬νμ¬ μΌκ΄ μ²λ¦¬λ κ°μ μμ±ν©λλ€. μ΄κ²μ΄ ν΄λμ€μ μ ν©νμ§ μμ κ²½μ° tf.experimental.ExtensionTypeBatchEncoder λ₯Ό μ¬μ©νμ¬ μ΄ κΈ°λ³Έ λμμ μ¬μ μν΄μΌ ν©λλ€. μλ₯Ό λ€μ΄, κ°λ³ ν¬μ ν
μμ values , indices λ° dense_shape tf.SparseTensor κ°μ λ°°μΉλ₯Ό λ§λλ κ²μ μ μ νμ§ μμ΅λλ€. λλΆλΆμ κ²½μ° μ΄λ¬ν ν
μλ νΈνλμ§ μλ λͺ¨μμ κ°μ§κ³ μκΈ° λλ¬Έμ μ€νν μ μμ΅λλ€. ; κ°λ₯νλλΌλ κ²°κ³Όλ μ ν¨ν SparseTensor .
μ°Έκ³ : BatchableExtensionType tf.stack , tf.concat , tf.slice λ±μ λν λμ€ν¨μ²λ₯Ό μλμΌλ‘ μ μνμ§ μμ΅λλ€ . μ΄λ¬ν APIμμ ν΄λμ€λ₯Ό μ§μν΄μΌ νλ κ²½μ° μμμ μ€λͺ
ν λμ€ν¨μΉ λ°μ½λ μ΄ν°λ₯Ό μ¬μ©νμΈμ.
BatchableExtensionType μ: λ€νΈμν¬
Network ν΄λμ€λ₯Ό μκ°ν΄ 보μμμ€. μ΄ ν΄λμ€λ κ° λ
Έλμμ μνν΄μΌ ν μμ
μ μκ³Ό λ
Έλ κ°μ μμ
μ μ΄λνλ λ° μ¬μ©ν μ μλ λμνμ μΆμ ν©λλ€. | class Network(tf.experimental.ExtensionType): # This version is not batchable.
work: tf.Tensor # work[n] = work left to do at node n
bandwidth: tf.Tensor # bandwidth[n1, n2] = bandwidth from n1->n2
net1 = Network([5., 3, 8], [[0., 2, 0], [2, 0, 3], [0, 3, 0]])
net2 = Network([3., 4, 2], [[0., 2, 2], [2, 0, 2], [2, 2, 0]]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 24e590ec6a8ef81d874edb7aa60df188 |
μ΄ μ νμ μΌκ΄ μ²λ¦¬ κ°λ₯νκ² λ§λ€λ €λ©΄ κΈ°λ³Έ μ νμ BatchableExtensionType λ³κ²½νκ³ μ νμ μΌκ΄ μ²λ¦¬ μ°¨μμ ν¬ν¨νλλ‘ κ° νλμ λͺ¨μμ μ‘°μ ν©λλ€. λ€μ μμ μμλ λ°°μΉ λͺ¨μμ μΆμ νκΈ° shape νλλ μΆκ°ν©λλ€. μ΄ shape νλλ νμλ‘νμ§ μλ tf.data.Dataset λλ tf.map_fn μμ§λ§ μꡬνλ tf.Keras . | class Network(tf.experimental.BatchableExtensionType):
shape: tf.TensorShape # batch shape. A single network has shape=[].
work: tf.Tensor # work[*shape, n] = work left to do at node n
bandwidth: tf.Tensor # bandwidth[*shape, n1, n2] = bandwidth from n1->n2
def __init__(self, work, bandwidth):
self.work = tf.convert_to_tensor(work)
self.bandwidth = tf.convert_to_tensor(bandwidth)
work_batch_shape = self.work.shape[:-1]
bandwidth_batch_shape = self.bandwidth.shape[:-2]
self.shape = work_batch_shape.merge_with(bandwidth_batch_shape)
def __repr__(self):
return network_repr(self)
def network_repr(network):
work = network.work
bandwidth = network.bandwidth
if hasattr(work, 'numpy'):
work = ' '.join(str(work.numpy()).split())
if hasattr(bandwidth, 'numpy'):
bandwidth = ' '.join(str(bandwidth.numpy()).split())
return (f"<Network shape={network.shape} work={work} bandwidth={bandwidth}>")
net1 = Network([5., 3, 8], [[0., 2, 0], [2, 0, 3], [0, 3, 0]])
net2 = Network([3., 4, 2], [[0., 2, 2], [2, 0, 2], [2, 2, 0]])
batch_of_networks = Network(
work=tf.stack([net1.work, net2.work]),
bandwidth=tf.stack([net1.bandwidth, net2.bandwidth]))
print(f"net1={net1}")
print(f"net2={net2}")
print(f"batch={batch_of_networks}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 97ec4e2441e650ae15650e5b4281349c |
tf.data.Dataset μ μ¬μ©νμ¬ λ€νΈμν¬ λ°°μΉλ₯Ό λ°λ³΅ν μ μμ΅λλ€. | dataset = tf.data.Dataset.from_tensor_slices(batch_of_networks)
for i, network in enumerate(dataset):
print(f"Batch element {i}: {network}") | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 80dc35c8bbb52fad9695dbea4d0dab20 |
map_fn μ μ¬μ©νμ¬ κ° λ°°μΉ μμμ ν¨μλ₯Ό μ μ©ν μλ μμ΅λλ€. | def balance_work_greedy(network):
delta = (tf.expand_dims(network.work, -1) - tf.expand_dims(network.work, -2))
delta /= 4
delta = tf.maximum(tf.minimum(delta, network.bandwidth), -network.bandwidth)
new_work = network.work + tf.reduce_sum(delta, -1)
return Network(new_work, network.bandwidth)
tf.map_fn(balance_work_greedy, batch_of_networks) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 9a33db2691085ab72cddab5ed96c1580 |
ExtensionTypesλ₯Ό μ§μνλ TensorFlow API
@tf.function
tf.function μ TensorFlow μ½λμ μ±λ₯μ ν¬κ² ν₯μμν¬ μ μλ Python ν¨μμ© TensorFlow κ·Έλνλ₯Ό 미리 κ³μ°νλ λ°μ½λ μ΄ν°μ
λλ€. @tf.function ν¨μμ ν¨κ» ν¬λͺ
νκ² μ¬μ©ν μ μμ΅λλ€. | class Pastry(tf.experimental.ExtensionType):
sweetness: tf.Tensor # 2d embedding that encodes sweetness
chewiness: tf.Tensor # 2d embedding that encodes chewiness
@tf.function
def combine_pastry_features(x: Pastry):
return (x.sweetness + x.chewiness) / 2
cookie = Pastry(sweetness=[1.2, 0.4], chewiness=[0.8, 0.2])
combine_pastry_features(cookie) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 63d63fc09c92dbe4e0d08d16452025ba |
input_signature λν΄ tf.function λ₯Ό λͺ
μμ μΌλ‘ μ§μ TypeSpec μ¬μ©νμ¬ μ§μ ν μ μμ΅λλ€. | pastry_spec = Pastry.Spec(tf.TensorSpec([2]), tf.TensorSpec(2))
@tf.function(input_signature=[pastry_spec])
def increase_sweetness(x: Pastry, delta=1.0):
return Pastry(x.sweetness + delta, x.chewiness)
increase_sweetness(cookie) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 044bd09ebce5a9429eed4808b3e6754c |
ꡬ체μ μΈ κΈ°λ₯
tf.function μν΄ κ΅¬μΆλ κ°λ³ μΆμ κ·Έλνλ₯Ό μΊ‘μνν©λλ€. νμ₯ μ νμ ꡬ체μ μΈ κΈ°λ₯κ³Ό ν¨κ» ν¬λͺ
νκ² μ¬μ©ν μ μμ΅λλ€. | cf = combine_pastry_features.get_concrete_function(pastry_spec)
cf(cookie) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | f37627e21e70385efc417fe15cc7cee3 |
μ μ΄ νλ¦ μμ
νμ₯ μ νμ TensorFlowμ μ μ΄ νλ¦ μμ
μμ μ§μλ©λλ€.
tf.cond
tf.case
tf.while_loop
tf.identity | # Example: using tf.cond to select between two MaskedTensors. Note that the
# two MaskedTensors don't need to have the same shape.
a = MaskedTensor([1., 2, 3], [True, False, True])
b = MaskedTensor([22., 33, 108, 55], [True, True, True, False])
condition = tf.constant(True)
print(tf.cond(condition, lambda: a, lambda: b))
# Example: using tf.while_loop with MaskedTensor.
cond = lambda i, _: i < 10
def body(i, mt):
return i + 1, mt.with_values(mt.values + 3 / 7)
print(tf.while_loop(cond, body, [0, b])[1]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | c83bcc13b45601cdf9260bacfaebaec4 |
μ¬μΈ μ μ΄ νλ¦
νμ₯ μ νμ tf.functionμ μ μ΄ νλ¦ λ¬Έμμλ μ§μλ©λλ€(autograph μ¬μ©). λ€μ μμμ if λ¬Έκ³Ό for λ¬Έμ νμ₯ μ νμ μ§μ tf.cond λ° tf.while_loop μμ
μΌλ‘ μλ λ³νλ©λλ€. | @tf.function
def fn(x, b):
if b:
x = MaskedTensor(x, tf.less(x, 0))
else:
x = MaskedTensor(x, tf.greater(x, 0))
for i in tf.range(5 if b else 7):
x = x.with_values(x.values + 1 / 2)
return x
print(fn(tf.constant([1., -2, 3]), tf.constant(True)))
print(fn(tf.constant([1., -2, 3]), tf.constant(False))) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | c8252206b963a7da687910c1730d0398 |
μΌλΌμ€
tf.keras λ λ₯ λ¬λ λͺ¨λΈμ ꡬμΆνκ³ νλ ¨νκΈ° μν TensorFlowμ κ³ κΈ APIμ
λλ€. νμ₯ μ νμ Keras λͺ¨λΈμ λν μ
λ ₯μΌλ‘ μ λ¬λκ³ , Keras κ³μΈ΅ κ°μ μ λ¬λκ³ , Keras λͺ¨λΈμμ λ°νλ μ μμ΅λλ€. Kerasλ νμ¬ νμ₯ μ νμ λ κ°μ§ μꡬ μ¬νμ μ μ©ν©λλ€.
λ°°μΉ κ°λ₯ν΄μΌ ν©λλ€(μμ "λ°°μΉ κ°λ₯ν ExtensionType" μ°Έμ‘°).
shape μ΄λΌλ νλ λλ μμ±μ΄ μμ΄μΌ ν©λλ€. shape[0] μ λ°°μΉ μ°¨μμΌλ‘ κ°μ£Όλ©λλ€.
λ€μ λ νμ μΉμ
μμλ νμ₯ μ νμ Kerasμ ν¨κ» μ¬μ©νλ λ°©λ²μ 보μ¬μ£Όλ μλ₯Ό μ 곡ν©λλ€.
Keras μ: Network
첫 λ²μ§Έ μμμλ λ
Έλ κ°μ λΆν λΆμ° μμ
μ μ¬μ©ν μ μλ μμ "Batchable ExtensionTypes" μΉμ
μ μ μλ Network κ·Έ μ μλ μ¬κΈ°μμ λ°λ³΅λ©λλ€. | class Network(tf.experimental.BatchableExtensionType):
shape: tf.TensorShape # batch shape. A single network has shape=[].
work: tf.Tensor # work[*shape, n] = work left to do at node n
bandwidth: tf.Tensor # bandwidth[*shape, n1, n2] = bandwidth from n1->n2
def __init__(self, work, bandwidth):
self.work = tf.convert_to_tensor(work)
self.bandwidth = tf.convert_to_tensor(bandwidth)
work_batch_shape = self.work.shape[:-1]
bandwidth_batch_shape = self.bandwidth.shape[:-2]
self.shape = work_batch_shape.merge_with(bandwidth_batch_shape)
def __repr__(self):
return network_repr(self)
single_network = Network( # A single network w/ 4 nodes.
work=[8.0, 5, 12, 2],
bandwidth=[[0.0, 1, 2, 2], [1, 0, 0, 2], [2, 0, 0, 1], [2, 2, 1, 0]])
batch_of_networks = Network( # Batch of 2 networks, each w/ 2 nodes.
work=[[8.0, 5], [3, 2]],
bandwidth=[[[0.0, 1], [1, 0]], [[0, 2], [2, 0]]]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 682f8cf0226763ad199827023800b1c5 |
Network λ₯Ό μ²λ¦¬νλ μλ‘μ΄ Keras κ³μΈ΅μ μ μν μ μμ΅λλ€. | class BalanceNetworkLayer(tf.keras.layers.Layer):
"""Layer that balances work between nodes in a network.
Shifts work from more busy nodes to less busy nodes, constrained by bandwidth.
"""
def call(self, inputs):
# This function is defined above, in "Batchable ExtensionTypes" section.
return balance_work_greedy(inputs) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 8758e00d1795d0dc915294f8b0d5e468 |
κ·Έλ° λ€μ μ΄ λ μ΄μ΄λ₯Ό μ¬μ©νμ¬ κ°λ¨ν λͺ¨λΈμ λ§λ€ μ μμ΅λλ€. ExtensionType μ λͺ¨λΈμ μ 곡νλ €λ©΄ type_spec μ΄ νμ₯ μ νμ TypeSpec tf.keras.layer.Input λ μ΄μ΄λ₯Ό μ¬μ©ν μ μμ΅λλ€. Keras λͺ¨λΈμ μ¬μ©νμ¬ λ°°μΉλ₯Ό μ²λ¦¬νλ κ²½μ° type_spec μ λ°°μΉ μ°¨μμ΄ ν¬ν¨λμ΄μΌ ν©λλ€. | input_spec = Network.Spec(shape=None,
work=tf.TensorSpec(None, tf.float32),
bandwidth=tf.TensorSpec(None, tf.float32))
model = tf.keras.Sequential([
tf.keras.layers.Input(type_spec=input_spec),
BalanceNetworkLayer(),
]) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | cd7a8ba20190183a804fe18c38b7fb95 |
λ§μ§λ§μΌλ‘ λ¨μΌ λ€νΈμν¬μ λ€νΈμν¬ λ°°μΉμ λͺ¨λΈμ μ μ©ν μ μμ΅λλ€. | model(single_network)
model(batch_of_networks) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6c41e93d1adf2fe7e56a649caa04a5fb |
μΌλΌμ€ μμ: MaskedTensor
μ΄ μμμ MaskedTensor Keras λ₯Ό μ§μνλλ‘ νμ₯λμμ΅λλ€. shape values νλμμ κ³μ°λλ μμ±μΌλ‘ μ μλ©λλ€. TypeSpec λͺ¨λμ μ΄ μμ±μ μΆκ°ν΄μΌ ν©λλ€. MaskedTensor SavedModel μ§λ ¬νμ νμν __name__ λ³μλ μ μν©λλ€(μλ μ°Έμ‘°). | class MaskedTensor(tf.experimental.BatchableExtensionType):
# __name__ is required for serialization in SavedModel; see below for details.
__name__ = 'extension_type_colab.MaskedTensor'
values: tf.Tensor
mask: tf.Tensor
shape = property(lambda self: self.values.shape)
dtype = property(lambda self: self.values.dtype)
def with_default(self, default):
return tf.where(self.mask, self.values, default)
def __repr__(self):
return masked_tensor_str(self.values, self.mask)
class Spec:
def __init__(self, shape, dtype=tf.float32):
self.values = tf.TensorSpec(shape, dtype)
self.mask = tf.TensorSpec(shape, tf.bool)
shape = property(lambda self: self.values.shape)
dtype = property(lambda self: self.values.dtype)
def with_shape(self):
return MaskedTensor.Spec(tf.TensorSpec(shape, self.values.dtype),
tf.TensorSpec(shape, self.mask.dtype)) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 87709f55a5ad3fdcd246851847ac5395 |
λ€μμΌλ‘ λμ€ν¨μΉ λ°μ½λ μ΄ν°λ μ¬λ¬ TensorFlow APIμ κΈ°λ³Έ λμμ μ¬μ μνλ λ° μ¬μ©λ©λλ€. μ΄λ¬ν APIλ νμ€ Keras λ μ΄μ΄(μ: Dense MaskedTensor μ ν¨κ» ν΄λΉ λ μ΄μ΄λ₯Ό μ¬μ©ν μ μμ΅λλ€. μ΄ μμ λͺ©μ μ matmul μ λ§μ€νΉλ κ°μ 0μΌλ‘ μ²λ¦¬νλλ‘ μ μλ©λλ€(μ¦, μ νμ ν¬ν¨νμ§ μκΈ° μν΄). | @tf.experimental.dispatch_for_unary_elementwise_apis(MaskedTensor)
def unary_elementwise_op_handler(op, x):
return MaskedTensor(op(x.values), x.mask)
@tf.experimental.dispatch_for_binary_elementwise_apis(
Union[MaskedTensor, tf.Tensor],
Union[MaskedTensor, tf.Tensor])
def binary_elementwise_op_handler(op, x, y):
x = convert_to_masked_tensor(x)
y = convert_to_masked_tensor(y)
return MaskedTensor(op(x.values, y.values), x.mask & y.mask)
@tf.experimental.dispatch_for_api(tf.matmul)
def masked_matmul(a: MaskedTensor, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
output_type=None):
if isinstance(a, MaskedTensor):
a = a.with_default(0)
if isinstance(b, MaskedTensor):
b = b.with_default(0)
return tf.matmul(a, b, transpose_a, transpose_b, adjoint_a,
adjoint_b, a_is_sparse, b_is_sparse, output_type) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 79879cc2ab73070cab7cd7290ebdba9a |
κ·Έλ° λ€μ νμ€ Keras λ μ΄μ΄λ₯Ό μ¬μ©νμ¬ MaskedTensor μ
λ ₯μ νμ©νλ Keras λͺ¨λΈμ ꡬμ±ν μ μμ΅λλ€. | input_spec = MaskedTensor.Spec([None, 2], tf.float32)
masked_tensor_model = tf.keras.Sequential([
tf.keras.layers.Input(type_spec=input_spec),
tf.keras.layers.Dense(16, activation="relu"),
tf.keras.layers.Dense(1)])
masked_tensor_model.compile(loss='binary_crossentropy', optimizer='rmsprop')
a = MaskedTensor([[1., 2], [3, 4], [5, 6]],
[[True, False], [False, True], [True, True]])
masked_tensor_model.fit(a, tf.constant([[1], [0], [1]]), epochs=3)
print(masked_tensor_model(a)) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 9efa4f45901f7ada6ad536851771af1e |
μ μ₯λ λͺ¨λΈ
SavedModel μ κ°μ€μΉμ κ³μ°μ λͺ¨λ ν¬ν¨νλ μ§λ ¬νλ TensorFlow νλ‘κ·Έλ¨μ
λλ€. Keras λͺ¨λΈ λλ μ¬μ©μ μ§μ λͺ¨λΈμμ ꡬμΆν μ μμ΅λλ€. λ κ²½μ° λͺ¨λ νμ₯ μ νμ SavedModelμ μν΄ μ μλ ν¨μ λ° λ©μλμ ν¨κ» ν¬λͺ
νκ² μ¬μ©λ μ μμ΅λλ€.
__name__ νλκ° μλ ν νμ₯ μ νμ μ²λ¦¬νλ λͺ¨λΈ, κ³μΈ΅ λ° ν¨μλ₯Ό μ μ₯ν μ μμ΅λλ€. μ΄ μ΄λ¦μ νμ₯ μ νμ λ±λ‘νλ λ° μ¬μ©λλ―λ‘ λͺ¨λΈμ λ‘λν λ μ°Ύμ μ μμ΅λλ€.
μ: Keras λͺ¨λΈ μ μ₯
νμ₯ μ νμ μ¬μ©νλ SavedModel μ¬μ©νμ¬ μ μ₯ν μ μμ΅λλ€. | masked_tensor_model_path = tempfile.mkdtemp()
tf.saved_model.save(masked_tensor_model, masked_tensor_model_path)
imported_model = tf.saved_model.load(masked_tensor_model_path)
imported_model(a) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 4fcf8152ff11dca05cd0f309b1235ae7 |
μ: μ¬μ©μ μ μ λͺ¨λΈ μ μ₯
SavedModelμ νμ₯ μ νμ μ²λ¦¬νλ ν¨μλ‘ tf.Module νμ ν΄λμ€λ₯Ό μ μ₯νλ λ° μ¬μ©ν μλ μμ΅λλ€. | class CustomModule(tf.Module):
def __init__(self, variable_value):
super().__init__()
self.v = tf.Variable(variable_value)
@tf.function
def grow(self, x: MaskedTensor):
"""Increase values in `x` by multiplying them by `self.v`."""
return MaskedTensor(x.values * self.v, x.mask)
module = CustomModule(100.0)
module.grow.get_concrete_function(MaskedTensor.Spec(shape=None,
dtype=tf.float32))
custom_module_path = tempfile.mkdtemp()
tf.saved_model.save(module, custom_module_path)
imported_model = tf.saved_model.load(custom_module_path)
imported_model.grow(MaskedTensor([1., 2, 3], [False, True, False])) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | e33d44ea33c1167bfefa82ee8cbf0983 |
ExtensionTypeμ μ¬μ©ν μ μμ λ μ μ₯λ λͺ¨λΈ λ‘λ
ExtensionType μ μ¬μ©νλ SavedModel μ λ‘λνμ§λ§ ν΄λΉ ExtensionType μ¬μ©ν μ μλ κ²½μ°(μ¦, κ°μ Έμ€μ§ μμ κ²½μ°) κ²½κ³ κ° νμλκ³ TensorFlowλ "μ΅λͺ
νμ₯ μ ν" κ°μ²΄λ₯Ό μ¬μ©νλλ‘ λ체ν©λλ€. μ΄ κ°μ²΄λ μλ μ νκ³Ό λμΌν νλλ₯Ό κ°μ§λ§ μ¬μ©μ μ μ λ©μλ λλ μμ±κ³Ό κ°μ΄ μ νμ μΆκ°ν μΆκ° μ¬μ©μ μ μκ° λΆμ‘±ν©λλ€.
TensorFlow μ 곡과 ν¨κ» ExtensionType μ¬μ©
νμ¬ TensorFlow μλΉμ€ (λ° SavedModel "μλͺ
" μ¬μ μ λ€λ₯Έ μλΉμ)λ λͺ¨λ μ
λ ₯ λ° μΆλ ₯μ΄ μμ ν
μκ° λμ΄μΌ ν©λλ€. νμ₯ μ νμ μ¬μ©νλ λͺ¨λΈκ³Ό ν¨κ» TensorFlow μλΉμ€λ₯Ό μ¬μ©νλ €λ κ²½μ° ν
μμμ νμ₯ μ ν κ°μ ꡬμ±νκ±°λ λΆν΄νλ λνΌ λ©μλλ₯Ό μΆκ°ν μ μμ΅λλ€. μ: | class CustomModuleWrapper(tf.Module):
def __init__(self, variable_value):
super().__init__()
self.v = tf.Variable(variable_value)
@tf.function
def var_weighted_mean(self, x: MaskedTensor):
"""Mean value of unmasked values in x, weighted by self.v."""
x = MaskedTensor(x.values * self.v, x.mask)
return (tf.reduce_sum(x.with_default(0)) /
tf.reduce_sum(tf.cast(x.mask, x.dtype)))
@tf.function()
def var_weighted_mean_wrapper(self, x_values, x_mask):
"""Raw tensor wrapper for var_weighted_mean."""
return self.var_weighted_mean(MaskedTensor(x_values, x_mask))
module = CustomModuleWrapper([3., 2., 8., 5.])
module.var_weighted_mean_wrapper.get_concrete_function(
tf.TensorSpec(None, tf.float32), tf.TensorSpec(None, tf.bool))
custom_module_path = tempfile.mkdtemp()
tf.saved_model.save(module, custom_module_path)
imported_model = tf.saved_model.load(custom_module_path)
x = MaskedTensor([1., 2., 3., 4.], [False, True, False, True])
imported_model.var_weighted_mean_wrapper(x.values, x.mask) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 9a7fd2a67bc61f8b07ff67ce7920c150 |
λ°μ΄ν°μΈνΈ
tf.data λ κ°λ¨νκ³ μ¬μ¬μ© κ°λ₯ν λΆλΆμΌλ‘ 볡μ‘ν μ
λ ₯ νμ΄νλΌμΈμ ꡬμΆν μ μλ APIμ
λλ€. ν΅μ¬ λ°μ΄ν° ꡬ쑰λ tf.data.Dataset μ΄λ©°, μ΄λ κ° μμκ° νλ μ΄μμ κ΅¬μ± μμλ‘ κ΅¬μ±λ μΌλ ¨μ μμλ₯Ό λνλ
λλ€.
νμ₯ μ νμΌλ‘ λ°μ΄ν°μΈνΈ λΉλ
Dataset.from_tensors , Dataset.from_tensor_slices λλ Dataset.from_generator μ¬μ©νμ¬ νμ₯ μ ν κ°μμ λ°μ΄ν° μΈνΈλ₯Ό λΉλν μ μμ΅λλ€. | ds = tf.data.Dataset.from_tensors(Pastry(5, 5))
iter(ds).next()
mt = MaskedTensor(tf.reshape(range(20), [5, 4]), tf.ones([5, 4]))
ds = tf.data.Dataset.from_tensor_slices(mt)
for value in ds:
print(value)
def value_gen():
for i in range(2, 7):
yield MaskedTensor(range(10), [j%i != 0 for j in range(10)])
ds = tf.data.Dataset.from_generator(
value_gen, output_signature=MaskedTensor.Spec(shape=[10], dtype=tf.int32))
for value in ds:
print(value) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 2477207abb42dca6f440ba426bf2e034 |
νμ₯ μ νμ΄ μλ λ°μ΄ν° μΈνΈ μΌκ΄ μ²λ¦¬ λ° μΌκ΄ ν΄μ
νμ₯ μ νμ λ°μ΄ν° μΈνΈλ₯Ό μ¬μ©νμ¬ batchand λ° unbatched μ μμ΅λλ€ Dataset.batch ADN Dataset.unbatch . | batched_ds = ds.batch(2)
for value in batched_ds:
print(value)
unbatched_ds = batched_ds.unbatch()
for value in unbatched_ds:
print(value) | site/ko/guide/extension_type.ipynb | tensorflow/docs-l10n | apache-2.0 | 6cf51e7c2710f3ea5781323b3a4685f6 |
The concrete loss function can be set via the loss parameter. SGDClassifier supports the following loss functions:
<ul>
<li>loss="hinge": (soft-margin) linear Support Vector Machine,
<li>loss="modified_huber": smoothed hinge loss,
<li>loss="log": logistic regression,
<li>and all regression losses below.
</ul>
The first two loss functions are lazy, they only update the model parameters if an example violates the margin constraint, which makes training very efficient and may result in sparser models, even when L2 penalty is used.
Using loss="log" or loss="modified_huber" enables the predict_proba method, which gives a vector of probability estimates P(y|x) per sample x: | clf = SGDClassifier(loss="log").fit(X, y)
clf.predict_proba([[1., 1.]]) | Lectures/Lecture6-Streams/SGD TESTING.ipynb | hethapu/big-data-python-class | mit | 87450905665bae4631fde9575806d05c |
The default setting is penalty="l2". The L1 penalty leads to sparse solutions, driving most coefficients to zero. The Elastic Net solves some deficiencies of the L1 penalty in the presence of highly correlated attributes. The parameter l1_ratio controls the convex combination of L1 and L2 penalty. | %matplotlib inline
# SGD: Maximum Margin Separating hyperplan
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.datasets.samples_generator import make_blobs
# we create 50 separable points
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
# fit the model
clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True)
clf.fit(X, Y)
# plot the line, the points, and the nearest vectors to the plane
xx = np.linspace(-1, 5, 10)
yy = np.linspace(-1, 5, 10)
X1, X2 = np.meshgrid(xx, yy)
Z = np.empty(X1.shape)
for (i, j), val in np.ndenumerate(X1):
x1 = val
x2 = X2[i, j]
p = clf.decision_function([x1, x2])
Z[i, j] = p[0]
levels = [-1.0, 0.0, 1.0]
linestyles = ['dashed', 'solid', 'dashed']
colors = 'k'
plt.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.axis('tight')
plt.show()
| Lectures/Lecture6-Streams/SGD TESTING.ipynb | hethapu/big-data-python-class | mit | 069030658e68ba7b64d2930686d63c38 |
customized_KoNLPy μλ νμ¬ νΈμν° νκ΅μ΄ λΆμκΈ° λ§μ μ΄μ©νλ wrapping classλ§ μ 곡λκ³ μμ΅λλ€. customized_KoNLPyμ Twitterλ λ³Έλ KoNLPyμ tagμ μΆκ°λλ ν¨μκ° μμ΅λλ€.
Twitter.add_dictionary(words, tag)λ μ¬μ©μκ° μ¬μ μ μΆκ°ν μ μλ λΆλΆμ
λλ€. λ¨μ΄λ₯Ό νλμ© μΆκ°ν μ μμ΅λλ€. μΆκ°ν λ€ Twitterμ μ¨κΉ λ³μμΈ _dictionary._pos2wordsλ₯Ό νμΈν΄λ³΄λ©΄ μ
λ ₯ν λ¨μ΄λ€μ λ³Ό μ μμ΅λλ€.
git cloneμ ν μνμμ tutorial codeλ₯Ό μ΄μ©νμ λ€λ©΄ μλμ μ½λλ₯Ό μ€ννμ¬ pathλ₯Ό μΆκ°νμμμ | import sys
sys.path.append('../')
from ckonlpy.tag import Twitter
twitter = Twitter()
twitter.add_dictionary('μ΄', 'Modifier')
twitter.add_dictionary('μ°λ¦¬', 'Modifier')
twitter.add_dictionary('μ΄λ²', 'Modifier')
twitter.add_dictionary('μμ΄μ€μμ΄', 'Noun')
twitter.add_dictionary('νμ¬', 'Noun')
twitter.add_dictionary('μμ΄', 'Noun')
twitter.add_dictionary('λ²κ²', 'Noun')
twitter.add_dictionary('κ²', 'Noun')
twitter.add_dictionary('μ', 'Josa')
twitter.add_dictionary('λ', 'Josa')
twitter._dictionary._pos2words | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 00f84f7ee3ffa3b124cf70cf540e9305 |
μ¬μ μ μΆκ°ν λ€, 'μμ΄μ€μμ΄'κ° λͺ
μ¬λ‘ μ λλ‘ μΈμλ¨μ νμΈν μ μμ΅λλ€. | twitter.pos('μ°λ¦¬μμ΄μ€μμ΄λ μ λ§ μ΄λ»μ')
twitter.pos('μμ΄μ€μμ΄ μ΄λ»μ') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 759279028f6bd2e152dd00ce4e28f29c |
μ¬μ μ μΆκ°ν λ, νλμ νμ¬μ λνμ¬ λμμ μ¬λ¬ κ°μ λ¨μ΄μ
μ μ
λ ₯ν μλ μμ΅λλ€.
Twitter.add_dictionary(words, tag)λ νλ²μ list of str νμμ μ¬λ¬ κ°μ λ¨μ΄λ€μ μ
λ ₯ν μλ μμ΅λλ€. | twitter.add_dictionary(['νΈμμ΄μ€', 'tt', 'νΈλ₯μ΄', 'κΊΌ', 'μ°λ¦¬'], 'Noun')
twitter._dictionary._pos2words
twitter.pos('νΈμμ΄μ€ttλ μ’μμ') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 997a518c1d14117c75e6748344035842 |
νΈμν° λΆμκΈ°μ μ‘°μ¬μ¬μ μ μ΄μ©ν μλ μμ΅λλ€. Twitter()λ₯Ό λ§λ€ λ argumentλ₯Ό λ£μ μ μμ΅λλ€. | twitter1 = Twitter(load_default_dictionary=True)
len(twitter1._dictionary._pos2words['Josa']) | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 5e6022bdb93143e1a6a3c33de12de1f0 |
νμ§λ§ μμ§ 'μ°λ¦¬νΈλ₯μ΄κΊΌttλ' μ΄λΌλ μ΄μ μ΄ μ λλ‘ μΈμλμ§ μμ΅λλ€. κ·Έ μ΄μ λ templatesμ 'Noun + Noun + Josa'κ° μμκΈ° λλ¬Έμ
λλ€. μ΄ κ²½μ°μλ KoNLPyμ ν΄λΉ μ΄μ μ λΆμνλΌκ³ 보λ
λλ€. νμ§λ§ 'νΈλ₯μ΄'λΌλ λ¨μ΄λ₯Ό μμ§ λͺ»ν΄μ μ λλ‘ μΈμλμ§ μμ΅λλ€. | twitter.pos('μ°λ¦¬νΈλ₯μ΄κΊΌttλ μ’μμ') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 9db0811c41aeb5efa7f3a6c531264e02 |
νμ¬λ customized_taggerλ‘ ν¬νλ¦Ώ κΈ°λ° ν ν¬λμ΄μ λ₯Ό μ΄μ©νκ³ μμ΅λλ€. μ΄λ€ ν¬νλ¦Ώμ΄ λ€μ΄μλμ§ νμΈνκΈ° μν΄μλ μλ λΆλΆμ νμΈνλ©΄ λ©λλ€.
twitter._customized_tagger.templates
νμ¬λ λ€μμ ν¬νλ¦Ώμ΄ μ
λ ₯λμ΄ μμ΅λλ€. | twitter._customized_tagger.templates | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | dcaa67d50950617cfd5a4986ae836f7a |
κΈ°λ³Έ ν¬νλ¦Ώμ customized_konlpy/data/templates/twitter_templates0 μ μ μ₯λμ΄ μμ΅λλ€. text νμμ νμΌμ΄λ©°, λμ΄μ°κΈ°λ‘ μλμ κ°μ κΈ°λ³Έ ν
νλ¦Ώμ μ§μ νλ©΄ λ©λλ€. | cat ../ckonlpy/data/templates/twitter_templates0 | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 1a4029d8d357eb3a7689c2d9473e2ec3 |
μμ
μ€ ν¬νλ¦Ώμ μΆκ°νκ³ μΆλ€λ©΄, ν¬νλ¦Ώμ νλ λ¨μλ‘ tuple of strμ νμμΌλ‘ μ
λ ₯ν μ μμ΅λλ€. _customized_tagger.add_a_templated()μ μ€λ³΅λλ ν¬νλ¦Ώμ΄ μλμ§ νμΈν λ€μ ν¬νλ¦Ώμ μΆκ°νλ ν¨μμ
λλ€. | twitter._customized_tagger.add_a_template(('Modifier', 'Noun', 'Noun', 'Noun', 'Josa'))
twitter._customized_tagger.templates | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | cdca3caa4c864a97a5c3ec35106cb483 |
('Noun', 'Noun', 'Josa')κ° μ
λ ₯λμκ³ , 'νΈμμ΄μ€', 'tt'κ° λͺ
μ¬μΈμ§ μκ³ μκΈ° λλ¬Έμ μλ λ¬Έμ₯μ μ λλ‘ μΈμμ΄ λ©λλ€. | twitter.pos('μ°λ¦¬νΈλ₯μ΄κΊΌttλ μ’μμ') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 68ab44e7bf5f536e3b0738e4ace7e6e1 |
μ¬μ μ μΆκ°ν λ, νΈμν° νκ΅μ΄ λΆμκΈ°μ μ‘΄μ¬νμ§ μλ νκ·Έκ° λ€μ΄κ°λ κ²μ λ°©μ§νκΈ° μν΄ tagμ κ°μ νμΈνλ λΆλΆμ΄ ꡬνλμ΄ μμ΅λλ€.
twitter.tagset
>>> {'Adjective': 'νμ©μ¬',
'Adverb': 'λΆμ¬',
'Alpha': 'μνλ²³',
'Conjunction': 'μ μμ¬',
'Determiner': 'κ΄νμ¬',
'Eomi': 'μ΄λ―Έ',
'Exclamation': 'κ°νμ¬',
'Foreign': 'μΈκ΅μ΄, νμ λ° κΈ°νκΈ°νΈ',
'Hashtag': 'νΈμν° ν΄μ¬νκ·Έ',
'Josa': 'μ‘°μ¬',
'KoreanParticle': '(ex: γ
γ
)',
'Modifier': 'κ΄νμ¬',
'Noun': 'λͺ
μ¬',
'Number': 'μ«μ',
'PreEomi': 'μ μ΄λ§μ΄λ―Έ',
'Punctuation': 'ꡬλμ ',
'ScreenName': 'νΈμν° μμ΄λ',
'Suffix': 'μ λ―Έμ¬',
'Unknown': 'λ―Έλ±λ‘μ΄',
'Verb': 'λμ¬'}
twitter.tagsetμ λ±λ‘λμ΄ μμ§ μλ νμ¬μ λν΄μλ ValueErrorλ₯Ό raise ν©λλ€. | twitter.add_dictionary('lovit', 'Name') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | c9e59e0acf3d94fe305014220d28824e |
νμ§λ§ Twitter.add_dictionary(words, tag, force=True)λ‘ λ¨μ΄λ₯Ό μ¬μ μ μ
λ ₯νλ©΄ μλ €μ§μ§ μμ νμ¬λΌ νλλΌλ μ
λ ₯ν μ μμ΅λλ€. | twitter.add_dictionary('lovit', 'Name', force=True)
twitter._dictionary._pos2words | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 8291e4a999bf2aa12a124aa26b0f9465 |
'Name'μ΄λΌλ ν΄λμ€ (λμ΄μ νμ¬κ° μλλ―λ‘)λ₯Ό μ΄μ©νλ ν¬νλ¦Ώμ νλ μ
λ ₯ν λ€ posμ μ
λ ₯νλ©΄ μ΄μ 'lovitμ' customized_taggerμ μνμ¬ μ²λ¦¬κ° λκ³ , μ¬μ©μ μ¬μ μ μλ €μ§μ§ μμ μ΄μ μΈ 'μ‘Έλ €'λ λ³Έλμ νΈμν° λΆμκΈ°μ μνμ¬ μ²λ¦¬κ° λ©λλ€. | twitter._customized_tagger.add_a_template(('Name', 'Josa'))
print(twitter._customized_tagger.templates)
twitter.pos('lovitμ μ΄λ¦μ
λλ€.') | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | 2ca26fd2c267408ac32d8a07ca5de3ca |
Templatesλ₯Ό μ΄μ©νμ¬λ νλ³΄κ° μ¬λ¬ κ° λμ¬ μ μμ΅λλ€. μ¬λ¬ κ° ν보 μ€μμ best λ₯Ό μ ννλ ν¨μλ₯Ό μ§μ λμμΈ ν μ λ μμ΅λλ€. μ΄μ²λΌ λͺ κ°μ μ μ κΈ°μ€μ λ§λ€κ³ , κ° κΈ°μ€μ weightλ₯Ό λΆμ¬νλ λ°©μμ νΈμν° λΆμκΈ°μμ μ΄μ©νλ λ°©μμΈλ°, μ§κ΄μ μ΄κ³ νλ κ°λ₯ν΄μ λ§€μ° μ’μ λ°©μμ΄λΌ μκ°ν©λλ€. | score_weights = {
'num_nouns': -0.1,
'num_words': -0.2,
'no_noun': -1
}
def my_score(candidate):
num_nouns = len([w for w,t in candidate if t == 'Noun'])
num_words = len(candidate)
no_noun = 1 if num_nouns == 0 else 0
score = (num_nouns * score_weights['num_nouns']
+ num_words * score_weights['num_words']
+ no_noun * score_weights['no_noun'])
return score
twitter.set_selector(score_weights, my_score) | customKonlpy/tutorials/usage_of_templatetagger.ipynb | TeamEmily/Emily_server | mit | ea3749008fdecf4510e99e06a2e1c537 |
1) Explore the dataset
Numerical exploration
Load the csv file into memory using Pandas
Describe each attribute
is it discrete?
is it continuous?
is it a number?
is it text?
Identify the target
Check if any values are missing
Load the csv file into memory using Pandas | df = pd.read_csv('titanic-train.csv') | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 004435b95066fb981740098519bdca0a |
What's the content of df ? | df.head(3) | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 51ab71c672f8bb6f6c385ca426b41802 |
Is Pclass a continuous or discrete class? | df['Pclass'].value_counts() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 15a579e74418ebbbd445b72ec20d36b9 |
What about these: ('SibSp', 'Parch')? | df['SibSp'].value_counts()
df['Parch'].value_counts() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 43087b46045c0fb2f274f7ad0bc799be |
and what about these: ('Ticket', 'Fare', 'Cabin', 'Embarked')? | df[['Ticket', 'Fare', 'Cabin']].head(3)
df['Embarked'].value_counts() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | fedbf4e59ffbd9410d90071a2404b376 |
Identify the target
What are we trying to predict?
ah, yes... Survival! | df['Survived'].value_counts() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 2d687309aef8582c3a4eb7b695407cda |
Mental notes so far:
Dataset contains 891 entries
1 Target column (Survived)
11 Features:
6 numerical, 5 text
1 useless (PassengerId)
3 categorical (Pclass, Sex, Embarked)
4 numerical, > 0 (Age, SibSp, Parch, Fare)
3 not sure how to treat (Name, Ticket, Cabin)
Age is only available for 714 passengers
Cabin is only available for 204 passengers
Embarked is missing for 2 passengers
Visual exploration
plot the distribution of Age
impute the missing values for Age using the median Age
check the influence of Age, Sex and Class on Survival
Plot the distribution of Age | df['Age'].plot(kind='hist', figsize=(10,6))
plt.title('Distribution of Age', size = '20')
plt.xlabel('Age', size = '20')
plt.ylabel('Number of passengers', size = '20')
median_age = df['Age'].median()
plt.axvline(median_age, color = 'r')
median_age | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | ab67877778d4929fc6718ccd0e67b544 |
impute the missing values for Age using the median Age | df['Age'].fillna(median_age, inplace = True)
df.info() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | e55b3855775444b41eedec9b119f7417 |
check the influence of Age | df[df['Survived']==1]['Age'].plot(kind='hist', bins = 10, range = (0,100), figsize=(10,6), alpha = 0.3, color = 'g')
df[df['Survived']==0]['Age'].plot(kind='hist', bins = 10, range = (0,100), figsize=(10,6), alpha = 0.3, color = 'r')
plt.title('Distribution of Age', size = '20')
plt.xlabel('Age', size = '20')
plt.ylabel('Number of passengers', size = '20')
plt.legend(['Survived', 'Dead'])
plt.show() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 0f244b371dd0e180aaddd29db7d059cd |
Check the influence of Sex on Survival | survival_by_gender = df[['Sex','Survived']].pivot_table(columns =
['Survived'], index = ['Sex'], aggfunc=len)
survival_by_gender
survival_by_gender.plot(kind = 'bar', stacked = True)
plt.show() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 4a148d4b26b3ae3722b23423d00636ab |
Check the influence of Pclass on Survival | survival_by_Pclass = df[['Pclass','Survived']].pivot_table(columns =
['Survived'], index = ['Pclass'], aggfunc=len)
survival_by_Pclass
survival_by_Pclass.plot(kind = 'bar', stacked = True)
plt.show() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 2b0cb8a68216e93c0e3ff21475730da1 |
Ok, so, Age and Pclass seem to have some influence on survival rate.
Let's build a simple model to test that
Define a new feature called "Male" that is 1 if Sex = 'male' and 0 otherwise | df['Male'] = df['Sex'].map({'male': 1, 'female': 0})
df[['Sex', 'Male']].head() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 9130ac2dd03761697b1892f63f78a376 |
Define simplest model as benchmark
The simplest model is a model that predicts 0 for everybody, i.e. no survival.
How good is it? | actual_dead = len(df[df['Survived'] == 0])
total_passengers = len(df)
ratio_of_dead = actual_dead / float(total_passengers)
print "If I predict everybody dies, I'm correct %0.1f %% of the time" % (100 * ratio_of_dead)
df['Survived'].value_counts() | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | e9723fb8c046dae9af1762c254cdc5d5 |
We need to do better than that
Define features (X) and target (y) variables | X = df[['Male', 'Pclass', 'Age']]
y = df['Survived'] | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 99269f99e12c5f2f6568e99e4ef153d4 |
Initialize a decision tree model | from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(random_state=0)
model | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | 8bcb93f2d8050df6395859fc9ddd7dc1 |
Split the features and the target into a Train and a Test subsets.
Ratio should be 80/20 | from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size = 0.2, random_state=0) | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | bac87139cb9b24c04878a2382b9a69d3 |
Print the confusion matrix for the decision tree model | from sklearn.metrics import confusion_matrix
y_pred = model.predict(X_test)
print "\n=======confusion matrix=========="
print confusion_matrix(y_test, y_pred) | Titanic Survival Workshop.ipynb | Dataweekends/odsc_intro_to_data_science | mit | d3a88ea27ec6c9677ce1b7fc11966498 |
Numpy: Arrays und effiziente Berechnungen
Das HerzstΓΌck von Numpy ist das Array. Dieser Datentyp reprΓ€sentiert eine Matrix und ist unter der Haube in C implementiert. Dabei wird groΓer Wert auf effiziente Speichernutzung gelegt. Der gΓ€ngige Satz "Python ist viel zu langsam" ist also nicht zwingend wahr. Wir kΓΆnnen Arrays auf verschiedene Arten erzeugen. | xs = np.array([1, 2, 3, 4]) # Konvertiert eine Python-Liste in ein Numpy-Array
print(xs)
ys = np.arange(4) # Erzeugt ein Array analog zur `range` Funktion
print(ys) | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | 8dc220ac508d3236ac7571747dc14e88 |
Numpy Arrays unterstΓΌtzen arithmetische Operationen, die wiederum effizient implementiert sind. Beispielsweise lassen sich zwei Arrays (elementweise) addieren sofern sie die gleichen Dimensionen haben. | xs + ys | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | d67dffedc432820303af1aad4d5afa70 |
Um einen Γberblick ΓΌber alle Features von Numpy zu bekommen, kΓΆnnen wir die Hilfe zu Rate ziehen. ZusΓ€tzlich zur help Funktion bietet IPython auch die ?-Magie mit einer besseren Integration in Jupyter | np? | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | d4f6f1504f0170445be97e87f5fe844f |
FΓΌr die Γbungsaufgaben werden wir hΓ€ufig Zufallszahlen brauchen. DafΓΌr bietet sich die Verwendung von np.random an. | np.random?
n_events = 10000
gauss = np.random.normal(2, 3, size=n_events) # Erzeuge 10000 GauΓ-verteilte Zufallszahlen
# mit Β΅=2 und Ο=3. | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | 3844e1995dea7be35e0be51641f9bf61 |
Matplotlib: SchΓΆne Plots
Matplotlib bietet sehr intuitive Funktionen um Daten darzustellen. Die sehr ausfΓΌhrliche Dokumentation bietet einen guten Γberblick. Wir benutzen an dieser Stelle nur das pyplot Submodul, das uns ein einfaches Interface fΓΌr die KernfunktionalitΓ€t bietet. In der Matplotlib Galerie finden sich viele schΓΆne Beispiele mit Codeschnipseln.
Um unsere GauΓ-verteilten Zufallszahlen zu histogrammieren benutzen wir einfach plt.hist. AuΓerdem setzen wir gleich Achsenbeschriftungen. | plt.hist(gauss)
plt.xlabel('Wert')
plt.ylabel('Absolute HΓ€ufigkeit') | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | 8cf65b1f1405a1054f2e102577f5925f |
Falls dir dieser Plot zu steril ist, kΓΆnnen wir den Stil der bekannten R-Bibliothek ggplot2 verwenden. | plt.style.use('ggplot') | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | 4303ccfe874f2cf746c947f8a487abe1 |
Wir wollen nun die Anzahl Bins erhΓΆhen und zusΓ€tzlich das Histogramm normieren, damit wir die normierte Verteilungsfunktion (PDF) eintragen kΓΆnnen. | plt.hist(gauss, bins=20, normed=True)
plt.xlabel('Wert')
plt.ylabel('Relative HΓ€ufigkeit') | tutorials/Wissenschaftliches Python Tutorial.ipynb | kdungs/teaching-SMD2-2016 | mit | 54c2bc8e31fc6aa79ae921192aee2185 |