markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
与普通张量一样,您可以使用 Python 算术和比较运算符来执行逐元素运算。有关更多信息,请参阅下面的**重载运算符**一节。 | print(digits + 3)
print(digits + tf.ragged.constant([[1, 2, 3, 4], [], [5, 6, 7], [8], []])) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
如果需要对 `RaggedTensor` 的值进行逐元素转换,您可以使用 `tf.ragged.map_flat_values`(它采用一个函数加上一个或多个参数的形式),并应用这个函数来转换 `RaggedTensor` 的值。 | times_two_plus_one = lambda x: x * 2 + 1
print(tf.ragged.map_flat_values(times_two_plus_one, digits)) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
不规则张量可以转换为嵌套的 Python `list` 和 numpy `array`: | digits.to_list()
digits.numpy() | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
构造不规则张量构造不规则张量的最简单方法是使用 `tf.ragged.constant`,它会构建与给定的嵌套 Python `list` 或 numpy `array` 相对应的 `RaggedTensor`: | sentences = tf.ragged.constant([
["Let's", "build", "some", "ragged", "tensors", "!"],
["We", "can", "use", "tf.ragged.constant", "."]])
print(sentences)
paragraphs = tf.ragged.constant([
[['I', 'have', 'a', 'cat'], ['His', 'name', 'is', 'Mat']],
[['Do', 'you', 'want', 'to', 'come', 'visit'], ["I'm", 'f... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
还可以通过将扁平的*值*张量与*行分区*张量进行配对来构造不规则张量,行分区张量使用 `tf.RaggedTensor.from_value_rowids`、`tf.RaggedTensor.from_row_lengths` 和 `tf.RaggedTensor.from_row_splits` 等工厂类方法指示如何将值分成各行。 `tf.RaggedTensor.from_value_rowids`如果知道每个值属于哪一行,可以使用 `value_rowids` 行分区张量构建 `RaggedTensor`:) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
`tf.RaggedTensor.from_row_lengths`如果知道每行的长度,可以使用 `row_lengths` 行分区张量: | print(tf.RaggedTensor.from_row_lengths(
values=[3, 1, 4, 1, 5, 9, 2],
row_lengths=[4, 0, 2, 1])) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
`tf.RaggedTensor.from_row_splits`如果知道指示每行开始和结束的索引,可以使用 `row_splits` 行分区张量: | print(tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7])) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
有关完整的工厂方法列表,请参阅 `tf.RaggedTensor` 类文档。注:默认情况下,这些工厂方法会添加断言,说明行分区张量结构良好且与值数量保持一致。如果您能够保证输入的结构良好且一致,可以使用 `validate=False` 参数跳过此类检查。 可以在不规则张量中存储什么与普通 `Tensor` 一样,`RaggedTensor` 中的所有值必须具有相同的类型;所有值必须处于相同的嵌套深度(张量的*秩*): | print(tf.ragged.constant([["Hi"], ["How", "are", "you"]])) # ok: type=string, rank=2
print(tf.ragged.constant([[[1, 2], [3]], [[4, 5]]])) # ok: type=int32, rank=3
try:
tf.ragged.constant([["one", "two"], [3, 4]]) # bad: multiple types
except ValueError as exception:
print(exception)
try:
tf.r... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
示例用例以下示例演示了如何使用 `RaggedTensor`,通过为每个句子的开头和结尾使用特殊标记,为一批可变长度查询构造和组合一元元组与二元元组嵌入。有关本例中使用的运算的更多详细信息,请参阅 `tf.ragged` 包文档。 | queries = tf.ragged.constant([['Who', 'is', 'Dan', 'Smith'],
['Pause'],
['Will', 'it', 'rain', 'later', 'today']])
# Create an embedding table.
num_buckets = 1024
embedding_size = 4
embedding_table = tf.Variable(
tf.random.truncated_normal([num_buckets, e... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
 不规则维度和均匀维度***不规则维度***是切片可能具有不同长度的维度。例如,`rt=[[3, 1, 4, 1], [], [5, 9, 2], [6], []]` 的内部(列)维度是不规则的,因为列切片 (`rt[0, :]`, ..., `rt[4, :]`) 具有不同的长度。切片全都具有相同长度的维度称为*均匀维度*。不规则张量的最外层维始终是均匀维度,因为它只包含一个切片(因此不可能有不同的切片长度)。其余维度可能是不规则维度也可能是均匀维度。例如... | tf.ragged.constant([["Hi"], ["How", "are", "you"]]).shape | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
可以使用方法 `tf.RaggedTensor.bounding_shape` 查找给定 `RaggedTensor` 的紧密边界形状: | print(tf.ragged.constant([["Hi"], ["How", "are", "you"]]).bounding_shape()) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
不规则张量和稀疏张量对比不规则张量*不*应该被认为是一种稀疏张量。尤其是,稀疏张量是以紧凑的格式对相同数据建模的 *tf.Tensor 的高效编码*;而不规则张量是对扩展的数据类建模的 *tf.Tensor 的延伸*。这种区别在定义运算时至关重要:- 对稀疏张量或密集张量应用某一运算应当始终获得相同结果。- 对不规则张量或稀疏张量应用某一运算可能获得不同结果。一个说明性的示例是,考虑如何为不规则张量和稀疏张量定义 `concat`、`stack` 和 `tile` 之类的数组运算。连接不规则张量时,会将每一行连在一起,形成一个具有组合长度的行:
ragged_y = tf.ragged.constant([["fell", "asleep"], ["barked"], ["is", "fuzzy"]])
print(tf.concat([ragged_x, ragged_y], axis=1)) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
但连接稀疏张量时,相当于连接相应的密集张量,如以下示例所示(其中 Ø 表示缺失的值): | sparse_x = ragged_x.to_sparse()
sparse_y = ragged_y.to_sparse()
sparse_result = tf.sparse.concat(sp_inputs=[sparse_x, sparse_y], axis=1)
print(tf.sparse.to_dense(sparse_result, '')) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
另一个说明为什么这种区别非常重要的示例是,考虑一个运算(如 `tf.reduce_mean`)的“每行平均值”的定义。对于不规则张量,一行的平均值是该行的值总和除以该行的宽度。但对于稀疏张量来说,一行的平均值是该行的值总和除以稀疏张量的总宽度(大于等于最长行的宽度)。 TensorFlow API Keras[tf.keras](https://tensorflow.google.cn/guide/keras) 是 TensorFlow 的高级 API,用于构建和训练深度学习模型。通过在 `tf.keras.Input` 或 `tf.keras.layers.InputLayer` 上设置 `ragged=True`,不规则张量... | # Task: predict whether each sentence is a question or not.
sentences = tf.constant(
['What makes you think she is a witch?',
'She turned me into a newt.',
'A newt?',
'Well, I got better.'])
is_question = tf.constant([True, False, True, False])
# Preprocess the input strings.
hash_buckets = 1000
wor... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
tf.Example[tf.Example](https://tensorflow.google.cn/tutorials/load_data/tfrecord) 是 TensorFlow 数据的标准 [protobuf](https://developers.google.com/protocol-buffers/) 编码。使用 `tf.Example` 编码的数据往往包括可变长度特征。例如,以下代码定义了一批具有不同特征长度的四条 `tf.Example` 消息: | import google.protobuf.text_format as pbtext
def build_tf_example(s):
return pbtext.Merge(s, tf.train.Example()).SerializeToString()
example_batch = [
build_tf_example(r'''
features {
feature {key: "colors" value {bytes_list {value: ["red", "blue"]} } }
feature {key: "lengths" value {int64_list {v... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
我们可以使用 `tf.io.parse_example` 解析这个编码数据,它采用序列化字符串的张量和特征规范字典,并将字典映射特征名称返回给张量。要将长度可变特征读入不规则张量,我们只需在特征规范字典中使用 `tf.io.RaggedFeature` 即可: | feature_specification = {
'colors': tf.io.RaggedFeature(tf.string),
'lengths': tf.io.RaggedFeature(tf.int64),
}
feature_tensors = tf.io.parse_example(example_batch, feature_specification)
for name, value in feature_tensors.items():
print("{}={}".format(name, value)) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
`tf.io.RaggedFeature` 还可用于读取具有多个不规则维度的特征。有关详细信息,请参阅 [API 文档](https://tensorflow.google.cn/api_docs/python/tf/io/RaggedFeature)。 数据集[tf.data](https://tensorflow.google.cn/guide/data) 是一个 API,可用于通过简单的可重用代码块构建复杂的输入流水线。它的核心数据结构是 `tf.data.Dataset`,表示一系列元素,每个元素包含一个或多个分量。 | # Helper function used to print datasets in the examples below.
def print_dictionary_dataset(dataset):
for i, element in enumerate(dataset):
print("Element {}:".format(i))
for (feature_name, feature_value) in element.items():
print('{:>14} = {}'.format(feature_name, feature_value)) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
使用不规则张量构建数据集可以采用通过 `tf.Tensor` 或 numpy `array` 构建数据集时使用的方法,如 `Dataset.from_tensor_slices`,通过不规则张量构建数据集: | dataset = tf.data.Dataset.from_tensor_slices(feature_tensors)
print_dictionary_dataset(dataset) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
注:`Dataset.from_generator` 目前还不支持不规则张量,但不久后将会支持这种张量。 批处理和取消批处理具有不规则张量的数据集可以使用 `Dataset.batch` 方法对具有不规则张量的数据集进行批处理(将 *n* 个连续元素组合成单个元素)。 | batched_dataset = dataset.batch(2)
print_dictionary_dataset(batched_dataset) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
相反,可以使用 `Dataset.unbatch` 将批处理后的数据集转换为扁平数据集。 | unbatched_dataset = batched_dataset.unbatch()
print_dictionary_dataset(unbatched_dataset) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
对具有可变长度非不规则张量的数据集进行批处理如果您有一个包含非不规则张量的数据集,而且各个元素的张量长度不同,则可以应用 `dense_to_ragged_batch` 转换,将这些非不规则张量批处理成不规则张量: | non_ragged_dataset = tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
non_ragged_dataset = non_ragged_dataset.map(tf.range)
batched_non_ragged_dataset = non_ragged_dataset.apply(
tf.data.experimental.dense_to_ragged_batch(2))
for element in batched_non_ragged_dataset:
print(element) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
转换具有不规则张量的数据集还可以使用 `Dataset.map` 创建或转换数据集中的不规则张量。 | def transform_lengths(features):
return {
'mean_length': tf.math.reduce_mean(features['lengths']),
'length_ranges': tf.ragged.range(features['lengths'])}
transformed_dataset = dataset.map(transform_lengths)
print_dictionary_dataset(transformed_dataset) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
tf.function[tf.function](https://tensorflow.google.cn/guide/function) 是预计算 Python 函数的 TensorFlow 计算图的装饰器,它可以大幅改善 TensorFlow 代码的性能。不规则张量能够透明地与 `@tf.function` 装饰的函数一起使用。例如,以下函数对不规则张量和非不规则张量均有效: | @tf.function
def make_palindrome(x, axis):
return tf.concat([x, tf.reverse(x, [axis])], axis)
make_palindrome(tf.constant([[1, 2], [3, 4], [5, 6]]), axis=1)
make_palindrome(tf.ragged.constant([[1, 2], [3], [4, 5, 6]]), axis=1) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
如果您希望为 `tf.function` 明确指定 `input_signature`,可以使用 `tf.RaggedTensorSpec` 执行此操作。 | @tf.function(
input_signature=[tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int32)])
def max_and_min(rt):
return (tf.math.reduce_max(rt, axis=-1), tf.math.reduce_min(rt, axis=-1))
max_and_min(tf.ragged.constant([[1, 2], [3], [4, 5, 6]])) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
具体函数[具体函数](https://tensorflow.google.cn/guide/functionobtaining_concrete_functions)封装通过 `tf.function` 构建的各个跟踪图。不规则张量可以透明地与具体函数一起使用。 | # Preferred way to use ragged tensors with concrete functions (TF 2.3+):
try:
@tf.function
def increment(x):
return x + 1
rt = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
cf = increment.get_concrete_function(rt)
print(cf(rt))
except Exception as e:
print(f"Not supported before TF 2.3: {type(e)}: {e}")... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
SavedModel[SavedModel](https://tensorflow.google.cn/guide/saved_model) 是序列化 TensorFlow 程序,包括权重和计算。它可以通过 Keras 模型或自定义模型构建。在任何一种情况下,不规则张量都可以透明地与 SavedModel 定义的函数和方法一起使用。 示例:保存 Keras 模型 | import tempfile
keras_module_path = tempfile.mkdtemp()
tf.saved_model.save(keras_model, keras_module_path)
imported_model = tf.saved_model.load(keras_module_path)
imported_model(hashed_words) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
示例:保存自定义模型 | class CustomModule(tf.Module):
def __init__(self, variable_value):
super(CustomModule, self).__init__()
self.v = tf.Variable(variable_value)
@tf.function
def grow(self, x):
return x * self.v
module = CustomModule(100.0)
# Before saving a custom model, we must ensure that concrete functions are
# bu... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
注:SavedModel [签名](https://tensorflow.google.cn/guide/saved_modelspecifying_signatures_during_export)是具体函数。如上文的“具体函数”部分所述,从 TensorFlow 2.3 开始,只有具体函数才能正确处理不规则张量。如果您需要在先前版本的 TensorFlow 中使用 SavedModel 签名,建议您将不规则张量分解成其张量分量。 重载运算符`RaggedTensor` 类会重载标准 Python 算术和比较运算符,使其易于执行基本的逐元素数学: | x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
y = tf.ragged.constant([[1, 1], [2], [3, 3, 3]])
print(x + y) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
由于重载运算符执行逐元素计算,因此所有二进制运算的输入必须具有相同的形状,或者可以广播至相同的形状。在最简单的广播情况下,单个标量与不规则张量中的每个值逐元素组合: | x = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
print(x + 3) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
有关更高级的用例,请参阅**广播**一节。不规则张量重载与正常 `Tensor` 相同的一组运算符:一元运算符 `-`、`~` 和 `abs()`;二元运算符 `+`、`-`、`*`、`/`、`//`、`%`、`**`、`&`、`|`、`^`、`==`、`` 和 `>=`。 索引不规则张量支持 Python 风格的索引,包括多维索引和切片。以下示例使用二维和三维不规则张量演示了不规则张量索引。 索引示例:二维不规则张量 | queries = tf.ragged.constant(
[['Who', 'is', 'George', 'Washington'],
['What', 'is', 'the', 'weather', 'tomorrow'],
['Goodnight']])
print(queries[1]) # A single query
print(queries[1, 2]) # A single word
print(queries[1:]) # Everything but the first row
pr... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
索引示例:三维不规则张量 | rt = tf.ragged.constant([[[1, 2, 3], [4]],
[[5], [], [6]],
[[7]],
[[8, 9], [10]]])
print(rt[1]) # Second row (2-D RaggedTensor)
print(rt[3, 0]) # First element of fourth row (1-D Tensor)
print(rt[:, 1:3... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
`RaggedTensor` 支持多维索引和切片,但有一个限制:不允许索引一个不规则维度。这种情况是有问题的,因为指示的值可能在某些行中存在,而在其他行中不存在。这种情况下,我们不知道是应该 (1) 引发 `IndexError`;(2) 使用默认值;还是 (3) 跳过该值并返回一个行数比开始时少的张量。根据 [Python 的指导原则](https://www.python.org/dev/peps/pep-0020/)(“当面对不明确的情况时,不要尝试去猜测”),我们目前不允许此运算。 张量类型转换`RaggedTensor` 类定义了可用于在 `RaggedTensor` 与 `tf.Tensor` 或 `tf.Sparse... | ragged_sentences = tf.ragged.constant([
['Hi'], ['Welcome', 'to', 'the', 'fair'], ['Have', 'fun']])
# RaggedTensor -> Tensor
print(ragged_sentences.to_tensor(default_value='', shape=[None, 10]))
# Tensor -> RaggedTensor
x = [[1, 3, -1, -1], [2, -1, -1, -1], [4, 5, 8, 9]]
print(tf.RaggedTensor.from_tensor(x, padding... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
评估不规则张量要访问不规则张量中的值,您可以:1. 使用 `tf.RaggedTensor.to_list()` 将不规则张量转换为嵌套 Python 列表。2. 使用 `tf.RaggedTensor.numpy()` 将不规则张量转换为 numpy 数组,数组的值是嵌套的 numpy 数组。3. 使用 `tf.RaggedTensor.values` 和 `tf.RaggedTensor.row_splits` 属性,或 `tf.RaggedTensor.row_lengths()` 和 `tf.RaggedTensor.value_rowids()` 之类的行分区方法,将不规则张量分解成其分量。4. 使用 Python 索引... | rt = tf.ragged.constant([[1, 2], [3, 4, 5], [6], [], [7]])
print("python list:", rt.to_list())
print("numpy array:", rt.numpy())
print("values:", rt.values.numpy())
print("splits:", rt.row_splits.numpy())
print("indexed value:", rt[1].numpy()) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
广播广播是使具有不同形状的张量在进行逐元素运算时具有兼容形状的过程。有关广播的更多背景,请参阅:- [Numpy:广播](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)- `tf.broadcast_dynamic_shape`- `tf.broadcast_to`广播两个输入 `x` 和 `y`,使其具有兼容形状的基本步骤是:1. 如果 `x` 和 `y` 没有相同的维数,则增加外层维度(使用大小 1),直至它们具有相同的维数。2. 对于 `x` 和 `y` 的大小不同的每一个维度: - 如果 `x` 或 `y` 在 `d` 维中的大小为 `1... | # x (2D ragged): 2 x (num_rows)
# y (scalar)
# result (2D ragged): 2 x (num_rows)
x = tf.ragged.constant([[1, 2], [3]])
y = 3
print(x + y)
# x (2d ragged): 3 x (num_rows)
# y (2d tensor): 3 x 1
# Result (2d ragged): 3 x (num_rows)
x = tf.ragged.constant(
[[10, 87, 12],
... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
下面是一些不广播的形状示例: | # x (2d ragged): 3 x (r1)
# y (2d tensor): 3 x 4 # trailing dimensions do not match
x = tf.ragged.constant([[1, 2], [3, 4, 5, 6], [7]])
y = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
try:
x + y
except tf.errors.InvalidArgumentError as exception:
print(exception)
# x (2d ragged): 3... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
RaggedTensor 编码不规则张量使用 `RaggedTensor` 类进行编码。在内部,每个 `RaggedTensor` 包含:- 一个 `values` 张量,它将可变长度行连接成扁平列表。- 一个 `row_partition`,它指示如何将这些扁平值分成各行。可以使用四种不同的编码存储 `row_partition`:- `row_splits` 是一个整型向量,用于指定行之间的拆分点。- `value_rowids` 是一个整型... | rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2],
row_splits=[0, 4, 4, 6, 7])
print(rt) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
选择为行分区使用哪种编码由不规则张量在内部进行管理,以提高某些环境下的效率。尤其是,不同行分区方案的某些优点和缺点是:- **高效索引**:`row_splits` 编码可以实现不规则张量的恒定时间索引和切片。- **高效连接**:`row_lengths` 编码在连接不规则张量时更有效,因为当两个张量连接在一起时,行长度不会改变。- **较小的编码大小**:`value_rowids` 编码在存储有大量空行的不规则张量时更有效,因为张量的大小只取决于值的总数。另一方面,`row_splits` 和 `row_lengths` 编码在存储具有较长行的不规则张量时更有效,因为它们每行只需要一个标量值。- **兼容性**:`value_... | rt = tf.RaggedTensor.from_row_splits(
values=tf.RaggedTensor.from_row_splits(
values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
row_splits=[0, 3, 3, 5, 9, 10]),
row_splits=[0, 1, 1, 5])
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_ran... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
工厂函数 `tf.RaggedTensor.from_nested_row_splits` 可用于通过提供一个 `row_splits` 张量列表,直接构造具有多个不规则维度的 RaggedTensor: | rt = tf.RaggedTensor.from_nested_row_splits(
flat_values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
nested_row_splits=([0, 1, 1, 5], [0, 3, 3, 5, 9, 10]))
print(rt) | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
不规则秩和扁平值不规则张量的***不规则秩***是底层 `values` 张量的分区次数(即 `RaggedTensor` 对象的嵌套深度)。最内层的 `values` 张量称为其 ***flat_values***。在以下示例中,`conversations` 具有 ragged_rank=3,其 `flat_values` 为具有 24 个字符串的一维 `Tensor`: | # shape = [batch, (paragraph), (sentence), (word)]
conversations = tf.ragged.constant(
[[[["I", "like", "ragged", "tensors."]],
[["Oh", "yeah?"], ["What", "can", "you", "use", "them", "for?"]],
[["Processing", "variable", "length", "data!"]]],
[[["I", "like", "cheese."], ["Do", "you?"]],
[["Y... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
均匀内层维度具有均匀内层维度的不规则张量通过为 flat_values(即最内层 `values`)使用多维 `tf.Tensor` 进行编码。 | rt = tf.RaggedTensor.from_row_splits(
values=[[1, 3], [0, 0], [1, 3], [5, 3], [3, 3], [1, 2]],
row_splits=[0, 3, 4, 6])
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_rank))
print("Flat values shape: {}".format(rt.flat_values.shape))
print("Flat value... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
均匀非内层维度具有均匀非内层维度的不规则张量通过使用 `uniform_row_length` 对行分区进行编码。 | rt = tf.RaggedTensor.from_uniform_row_length(
values=tf.RaggedTensor.from_row_splits(
values=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
row_splits=[0, 3, 5, 9, 10]),
uniform_row_length=2)
print(rt)
print("Shape: {}".format(rt.shape))
print("Number of partitioned dimensions: {}".format(rt.ragged_r... | _____no_output_____ | Apache-2.0 | site/zh-cn/guide/ragged_tensor.ipynb | RedContritio/docs-l10n |
Data Space Report Pittsburgh Bridges Data Set Andy Warhol Bridge - Pittsburgh.Report created by Student Francesco Maria Chiarlo s253666, for A.A 2019/2020.**Abstract**:The aim of this report is to evaluate the effectiveness of distinct, different statistical learning approaches, in particular focusing on their char... | # =========================================================================== #
# STANDARD IMPORTS
# =========================================================================== #
print(__doc__)
from pprint import pprint
import warnings
warnings.filterwarnings('ignore')
import copy
import os
import sys
import time
i... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Dataset's Attributes Description The analyses that I aim at accomplishing while using as means the methods or approaches provided by both Statistical Learning and Machine Learning fields, concern the dataset Pittsburgh Bridges, and what follows is a overview and brief description of the main characteristics, as well a... | # =========================================================================== #
# READ INPUT DATASET
# =========================================================================== #
dataset_path = 'C:\\Users\\Francesco\Documents\\datasets\\pittsburgh_dataset'
dataset_name = 'bridges.data.csv'
# column_names = ['IDENTI... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
What we can notice from just the table above is that there are some attributes that are characterized by a special character that is '?' which stands for a missing value, so by chance there was not possibility to get the value for this attribute, such as for LENGTH and SPAN attributes. Analyzing in more details the dat... | # INVESTIGATING DATASET IN ORDER TO DETECT NULL VALUES
# --------------------------------------------------------------------------- #
print('Before preprocessing dataset and handling null values')
result = dataset.isnull().values.any()
print('There are any null values ? Response: {}'.format(result))
result = dataset.... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
The next step is represented by the effort of mapping categorical variables into numerical variables, so that them are comparable with the already existing numerical or continuous variables, and also by mapping the categorical variables into numerical variables we allow or enable us to perform some kind of normalizatio... | # MAP NUMERICAL VALUES TO INTEGER VALUES
# --------------------------------------------------------------------------- #
print('Before', dataset.shape)
columns_2_map = ['ERECTED', 'LANES']
for _, predictor in enumerate(columns_2_map):
dataset = dataset[dataset[predictor] != '?']
dataset[predictor] = np.array(li... | shape features matrix X, after normalizing: (70, 11)
| MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Pricipal Component AnalysisAfter having investigate the data points inside the dataset, I move one to another section of my report where I decide to explore examples that made up the entire dataset using a particular technique in the field of statistical analysis that corresponds, precisely, to so called Principal Com... | n_components = rescaledX.shape[1]
pca = PCA(n_components=n_components)
# pca = PCA(n_components=2)
# X_pca = pca.fit_transform(X)
pca = pca.fit(rescaledX)
X_pca = pca.transform(rescaledX)
print(f"Cumulative varation explained(percentage) up to given number of pcs:")
tmp_data = []
principal_components = [pc for pc in ... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Major Pros & Cons of PCA Learning Models | # Parameters to be tested for Cross-Validation Approach
estimators_list = [GaussianNB(), LogisticRegression(), KNeighborsClassifier(), SVC(), DecisionTreeClassifier(), RandomForestClassifier()]
estimators_names = ['GaussianNB', 'LogisticRegression', 'KNeighborsClassifier', 'SVC', 'DecisionTreeClassifier', 'RandomFores... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
PCA = 2 | plot_dest = os.path.join("figures", "n_comp_2_analysis")
N_CV, N_KERNEL = 9, 4
assert len(cv_list) >= N_CV, f"Error: N_CV={N_CV} > len(cv_list)={len(cv_list)}"
assert len(pca_kernels_list) >= N_KERNEL, f"Error: N_KERNEL={N_KERNEL} > len(pca_kernels_list)={len(pca_kernels_list)}"
X = rescaledX
n = len(estimators_list)... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
PCA = 9 | plot_dest = os.path.join("figures", "n_comp_9_analysis")
n = len(estimators_list) # len(estimators_list)
pos = 0
dfs_list, df_strfd = fit_all_by_n_components(
estimators_list=estimators_list[:n], \
estimators_names=estimators_names[:n], \
X=X, \
y=y, \
n_components=9, \
show_plots=False, \
c... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
PCA = 12 | plot_dest = os.path.join("figures", "n_comp_12_analysis")
n = len(estimators_list) # len(estimators_list)
pos = 0
dfs_list, df_strfd = fit_all_by_n_components(
estimators_list=estimators_list[:n], \
estimators_names=estimators_names[:n], \
X=X, \
y=y, \
n_components=12, \
show_plots=False, \
... | _____no_output_____ | MIT | pittsburgh-bridges-data-set-analysis/backup/Data Space Report (Official) - Two-Dimensional Analyses-v1.0.1.ipynb | franec94/Pittsburgh-Bridge-Dataset |
Setup First, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed (although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead), as well as Scikit-Learn ≥0.20. | # Python ≥3.5 is required
import sys
assert sys.version_info >= (3, 5)
# Scikit-Learn ≥0.20 is required
import sklearn
assert sklearn.__version__ >= "0.20"
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline... | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Linear SVM Classification The next few code cells generate the first figures in chapter 5. The first actual code sample comes after.**Code to generate Figure 5–1. Large margin classification** | from sklearn.svm import SVC
from sklearn import datasets
iris = datasets.load_iris()
X = iris["data"][:, (2, 3)] # petal length, petal width
y = iris["target"]
setosa_or_versicolor = (y == 0) | (y == 1)
X = X[setosa_or_versicolor]
y = y[setosa_or_versicolor]
# SVM Classifier model
svm_clf = SVC(kernel="linear", C=f... | Saving figure large_margin_classification_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–2. Sensitivity to feature scales** | Xs = np.array([[1, 50], [5, 20], [3, 80], [5, 60]]).astype(np.float64)
ys = np.array([0, 0, 1, 1])
svm_clf = SVC(kernel="linear", C=100)
svm_clf.fit(Xs, ys)
plt.figure(figsize=(9,2.7))
plt.subplot(121)
plt.plot(Xs[:, 0][ys==1], Xs[:, 1][ys==1], "bo")
plt.plot(Xs[:, 0][ys==0], Xs[:, 1][ys==0], "ms")
plot_svc_decision_b... | Saving figure sensitivity_to_feature_scales_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Soft Margin Classification**Code to generate Figure 5–3. Hard margin sensitivity to outliers** | X_outliers = np.array([[3.4, 1.3], [3.2, 0.8]])
y_outliers = np.array([0, 0])
Xo1 = np.concatenate([X, X_outliers[:1]], axis=0)
yo1 = np.concatenate([y, y_outliers[:1]], axis=0)
Xo2 = np.concatenate([X, X_outliers[1:]], axis=0)
yo2 = np.concatenate([y, y_outliers[1:]], axis=0)
svm_clf2 = SVC(kernel="linear", C=10**9)
... | Saving figure sensitivity_to_outliers_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**This is the first code example in chapter 5:** | import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
iris = datasets.load_iris()
X = iris["data"][:, (2, 3)] # petal length, petal width
y = (iris["target"] == 2).astype(np.float64) # Iris virginica
s... | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–4. Large margin versus fewer margin violations** | scaler = StandardScaler()
svm_clf1 = LinearSVC(C=1, loss="hinge", random_state=42)
svm_clf2 = LinearSVC(C=100, loss="hinge", random_state=42)
scaled_svm_clf1 = Pipeline([
("scaler", scaler),
("linear_svc", svm_clf1),
])
scaled_svm_clf2 = Pipeline([
("scaler", scaler),
("linear_svc",... | Saving figure regularization_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Nonlinear SVM Classification **Code to generate Figure 5–5. Adding features to make a dataset linearly separable** | X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
X2D = np.c_[X1D, X1D**2]
y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
plt.figure(figsize=(10, 3))
plt.subplot(121)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
plt.gca().get_ya... | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Here is second code example in the chapter:** | from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
polynomial_svm_clf = Pipeline([
("poly_features", PolynomialFeatures(degree=3)),
("scaler", StandardScaler()),
("svm_clf", LinearSVC(C=10, loss="hinge", random_stat... | C:\Users\kleme\anaconda3\envs\ML_Fundamentals\lib\site-packages\sklearn\svm\_base.py:1206: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.
warnings.warn(
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–6. Linear SVM classifier using polynomial features** | def plot_predictions(clf, axes):
x0s = np.linspace(axes[0], axes[1], 100)
x1s = np.linspace(axes[2], axes[3], 100)
x0, x1 = np.meshgrid(x0s, x1s)
X = np.c_[x0.ravel(), x1.ravel()]
y_pred = clf.predict(X).reshape(x0.shape)
y_decision = clf.decision_function(X).reshape(x0.shape)
plt.contourf(x... | Saving figure moons_polynomial_svc_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Polynomial Kernel **Next code example:** | from sklearn.svm import SVC
poly_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
])
poly_kernel_svm_clf.fit(X, y) | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–7. SVM classifiers with a polynomial kernel** | poly100_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
])
poly100_kernel_svm_clf.fit(X, y)
fig, axes = plt.subplots(ncols=2, figsize=(10.5, 4), sharey=True)
plt.sca(axes[0])
plot_predictions(poly_kernel_svm_clf, [-1.5, 2.45, -1, ... | Saving figure moons_kernelized_polynomial_svc_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Similarity Features **Code to generate Figure 5–8. Similarity features using the Gaussian RBF** | def gaussian_rbf(x, landmark, gamma):
return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
gamma = 0.3
x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
x2s = gaussian_rbf(x1s, -2, gamma)
x3s = gaussian_rbf(x1s, 1, gamma)
XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
yk = np.arr... | Phi(-1.0, -2) = [0.74081822]
Phi(-1.0, 1) = [0.30119421]
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
Gaussian RBF Kernel **Next code example:** | rbf_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
])
rbf_kernel_svm_clf.fit(X, y) | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–9. SVM classifiers using an RBF kernel** | from sklearn.svm import SVC
gamma1, gamma2 = 0.1, 5
C1, C2 = 0.001, 1000
hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
svm_clfs = []
for gamma, C in hyperparams:
rbf_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=gamma, ... | Saving figure moons_rbf_svc_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
SVM Regression | np.random.seed(42)
m = 50
X = 2 * np.random.rand(m, 1)
y = (4 + 3 * X + np.random.randn(m, 1)).ravel() | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Next code example:** | from sklearn.svm import LinearSVR
svm_reg = LinearSVR(epsilon=1.5, random_state=42)
svm_reg.fit(X, y) | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–10. SVM Regression** | svm_reg1 = LinearSVR(epsilon=1.5, random_state=42)
svm_reg2 = LinearSVR(epsilon=0.5, random_state=42)
svm_reg1.fit(X, y)
svm_reg2.fit(X, y)
def find_support_vectors(svm_reg, X, y):
y_pred = svm_reg.predict(X)
off_margin = (np.abs(y - y_pred) >= svm_reg.epsilon)
return np.argwhere(off_margin)
svm_reg1.supp... | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Note**: to be future-proof, we set `gamma="scale"`, as this will be the default value in Scikit-Learn 0.22. **Next code example:** | from sklearn.svm import SVR
svm_poly_reg = SVR(kernel="poly", degree=2, C=100, epsilon=0.1, gamma="scale")
svm_poly_reg.fit(X, y) | _____no_output_____ | Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
**Code to generate Figure 5–11. SVM Regression using a second-degree polynomial kernel** | from sklearn.svm import SVR
svm_poly_reg1 = SVR(kernel="poly", degree=2, C=100, epsilon=0.1, gamma="scale")
svm_poly_reg2 = SVR(kernel="poly", degree=2, C=0.01, epsilon=0.1, gamma="scale")
svm_poly_reg1.fit(X, y)
svm_poly_reg2.fit(X, y)
fig, axes = plt.subplots(ncols=2, figsize=(9, 4), sharey=True)
plt.sca(axes[0])
pl... | Saving figure svm_with_polynomial_kernel_plot
| Apache-2.0 | 05_support_vector_machines.ipynb | Schnatz65/ML_Fundamentals |
%matplotlib inline
import numpy as np
import tensorflow as tf
print(tf.__version__)
!pip install git+https://github.com/tensorflow/docs
import tensorflow_docs as tfdocs
import tensorflow_docs.plots
import tensorflow_docs.modeling
from google.colab import drive
drive.mount('/content/gdrive')
import pandas as pd
df=pd.... | Confusion Matrix
| Apache-2.0 | SS_AITrader_INTC.ipynb | JamesHorrex/AI_stock_trading | |
# Make inline plots vector graphics instead of raster graphics
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('pdf', 'svg')
import pandas as pd
import plotly.express as px
cereals = pd.read_csv("https://github.com/briandk/2020-virtual-program-in-data-science/raw/master/data/cereals.csv")
cer... | _____no_output_____ | MIT | cereals.ipynb | briandk/2020-virtual-program-in-data-science | |
Deriving a Point-Spread Function in a Crowded Field following Appendix III of Peter Stetson's *User's Manual for DAOPHOT II* Using `pydaophot` form `astwro` python package All *italic* text here have been taken from Stetson's manual. The only input file for this procedure is a FITS file containing reference frame imag... | from astwro.sampledata import fits_image
frame = fits_image() | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
`Daophot` object creates temporary working directory (*runner directory*), which is passed to `Allstar` constructor to share. | from astwro.pydaophot import Daophot, Allstar
dp = Daophot(image=frame)
al = Allstar(dir=dp.dir) | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Daophot got FITS file in construction, which will be automatically **ATTACH**ed. *(1) Run FIND on your frame* Daophot `FIND` parameters `Number of frames averaged, summed` are defaulted to `1,1`, below are provided for clarity. | res = dp.FInd(frames_av=1, frames_sum=1) | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Check some results returned by `FIND`, every method for `daophot` command returns results object. | print ("{} pixels analysed, sky estimate {}, {} stars found.".format(res.pixels, res.sky, res.stars)) | 9640 pixels analysed, sky estimate 12.665, 4166 stars found.
| MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Also, take a look into *runner directory* | !ls -lt $dp.dir | total 536
lrwxr-xr-x 1 michal staff 60 Jun 26 18:25 [35m63d38b_NGC6871.fits[m[m -> /Users/michal/projects/astwro/astwro/sampledata/NGC6871.fits
lrwxr-xr-x 1 michal staff 65 Jun 26 18:25 [35mallstar.opt[m[m -> /Users/michal/projects/astwro/astwro/pydaophot/config/allstar.opt
lrwxr-xr-x 1 michal ... | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
We see symlinks to input image and `opt` files, and `i.coo` - result of `FIND` *(2) Run PHOTOMETRY on your frame* Below we run photometry, providing explicitly radius of aperture `A1` and `IS`, `OS` sky radiuses. | res = dp.PHotometry(apertures=[8], IS=35, OS=50) | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
List of stars generated by daophot commands, can be easily get as `astwro.starlist.Starlist` being essentially `pandas.DataFrame`: | stars = res.photometry_starlist | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Let's check 10 stars with least A1 error (``mag_err`` column). ([pandas](https://pandas.pydata.org) style) | stars.sort_values('mag_err').iloc[:10] | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*(3) SORT the output from PHOTOMETRY**in order of increasing apparent magnitude decreasingstellar brightness with the renumbering feature. This step is optional but it can be more convenient than not.* `SORT` command of `daophor` is not implemented (yet) in `pydaohot`. But we do sorting by ourself. | sorted_stars = stars.sort_values('mag')
sorted_stars.renumber() | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Here we write sorted list back info photometry file at default name (overwriting existing one), because it's convenient to use default files in next commands. | dp.write_starlist(sorted_stars, 'i.ap')
!head -n20 $dp.PHotometry_result.photometry_file
dp.PHotometry_result.photometry_file | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*(4) PICK to generate a set of likely PSF stars* *How many stars you want to use is a function of the degree of variation you expect and the frequency with which stars are contaminated by cosmic rays or neighbor stars. [...]* | pick_res = dp.PIck(faintest_mag=20, number_of_stars_to_pick=40) | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
If no error reported, symlink to image file (renamed to `i.fits`), and all daophot output files (`i.*`) are in the working directory of runner: | ls $dp.dir | [35m63d38b_NGC6871.fits[m[m@ [35mdaophot.opt[m[m@ i.coo
[35mallstar.opt[m[m@ i.ap i.lst
| MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
One may examine and improve `i.lst` list of PSF stars. Or use `astwro.tools.gapick.py` to obtain list of PSF stars optimised by genetic algorithm. *(5) Run PSF **tell it the name of your complete (sorted renumbered) aperture photometry file, the name of the file with the list of PSF stars, and the name of the ... | dp.set_options('VARIABLE PSF', 2)
psf_res = dp.PSf() | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*(6) Run GROUP and NSTAR or ALLSTAR on your NEI file**If your PSF stars have many neighbors this may take some minutes of real time. Please be patient or submit it as a batch job and perform steps on your next frame while you wait.* We use `allstar`. (`GROUP` and `NSTAR` command are not implemented in current... | alls_res = al.ALlstar(image_file=frame, stars=psf_res.nei_file, subtracted_image_file='is.fits') | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
All `result` objects, has `get_buffer()` method, useful to lookup unparsed `daophot` or `allstar` output: | print (alls_res.get_buffer()) | 63d38b_NGC6871...
Picture size: 1250 1150
File with the PSF (default 63d38b_NGC6871.psf): Input file (default 63d38b_NGC6871.ap): File for results (default i.als): Name for subtracted image (default is... | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*(8) EXIT from DAOPHOT and send this new picture to the image display * *Examine each of the PSF stars and its environs. Have all of the PSF stars subtracted out more or less cleanly, or should some of them be rejected from further use as PSF stars? (If so use a text editor to delete these stars from the LST fil... | sub_img = alls_res.subtracted_image_file | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
We can also generate region file for psf stars: | from astwro.starlist.ds9 import write_ds9_regions
reg_file_path = dp.file_from_runner_dir('lst.reg')
write_ds9_regions(pick_res.picked_starlist, reg_file_path)
# One can run ds9 directly from notebook:
!ds9 $sub_img -regions $reg_file_path | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*(9) Back in DAOPHOT II ATTACH the original picture and run SUBSTAR**specifying the file created in step (6) or in step (8f) as the stars to subtract, and the stars in the LST file as the stars to keep.* Lookup into runner dir: | ls $al.dir
sub_res = dp.SUbstar(subtract=alls_res.profile_photometry_file, leave_in=pick_res.picked_stars_file) | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*You have now created a new picture which has the PSF stars still in it but from which the known neighbors of these PSF stars have been mostly removed* (10) ATTACH the new star subtracted frame and repeat step (5) to derive a new point spread function (11+...) Run GROUP NSTAR or ALLSTAR | for i in range(3):
print ("Iteration {}: Allstar chi: {}".format(i, alls_res.als_stars.chi.mean()))
dp.image = 'is.fits'
respsf = dp.PSf()
print ("Iteration {}: PSF chi: {}".format(i, respsf.chi))
alls_res = al.ALlstar(image_file=frame, stars='i.nei')
dp.image = frame
dp.SUbstar(subtract='i.... | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Check last image with subtracted PSF stars neighbours. | !ds9 $dp.SUbstar_result.subtracted_image_file -regions $reg_file_path | _____no_output_____ | MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
*Once you have produced a frame in which the PSF stars and their neighbors all subtract out cleanly, one more time through PSF should produce a point-spread function you can be proud of.* | dp.image = 'is.fits'
psf_res = dp.PSf()
print ("PSF file: {}".format(psf_res.psf_file)) | PSF file: /var/folders/kt/1jqvm3s51jd4qbxns7dc43rw0000gq/T/pydaophot_tmpDu5p8c/i.psf
| MIT | examples/deriving_psf_stenson.ipynb | majkelx/astwro |
Fitting Models Exercise 1 Imports | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt | _____no_output_____ | MIT | assignments/assignment12/FittingModelsEx01.ipynb | rsterbentz/phys202-2015-work |
Fitting a quadratic curve For this problem we are going to work with the following model:$$ y_{model}(x) = a x^2 + b x + c $$The true values of the model parameters are as follows: | a_true = 0.5
b_true = 2.0
c_true = -4.0 | _____no_output_____ | MIT | assignments/assignment12/FittingModelsEx01.ipynb | rsterbentz/phys202-2015-work |
First, generate a dataset using this model using these parameters and the following characteristics:* For your $x$ data use 30 uniformly spaced points between $[-5,5]$.* Add a noise term to the $y$ value at each point that is drawn from a normal distribution with zero mean and standard deviation 2.0. Make sure you add ... | def quad(x,a,b,c):
return a*x**2 + b*x + c
N = 30
xdata = np.linspace(-5,5,N)
dy = 2.0
np.random.seed(0)
ydata = quad(xdata,a_true,b_true,c_true) + np.random.normal(0.0, dy, N)
plt.errorbar(xdata,ydata,dy,fmt='.k',ecolor='lightgrey')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-5,5);
assert True # leave this cell for... | _____no_output_____ | MIT | assignments/assignment12/FittingModelsEx01.ipynb | rsterbentz/phys202-2015-work |
Now fit the model to the dataset to recover estimates for the model's parameters:* Print out the estimates and uncertainties of each parameter.* Plot the raw data and best fit of the model. | theta_best, theta_cov = opt.curve_fit(quad, xdata, ydata, sigma=dy)
a_fit = theta_best[0]
b_fit = theta_best[1]
c_fit = theta_best[2]
print('a = {0:.3f} +/- {1:.3f}'.format(a_fit, np.sqrt(theta_cov[0,0])))
print('b = {0:.3f} +/- {1:.3f}'.format(b_fit, np.sqrt(theta_cov[1,1])))
print('c = {0:.3f} +/- {1:.3f}'.format(c_f... | _____no_output_____ | MIT | assignments/assignment12/FittingModelsEx01.ipynb | rsterbentz/phys202-2015-work |
内容- lightGBMモデル初版- ターゲットエンコーディング:Holdout TS- 外部データ3つ(ステージ面積1,ステージ面積2,ブキ)を結合 - ステージ面積1: https://probspace-stg.s3-ap-northeast-1.amazonaws.com/uploads/user/c10947bba5cde4ad3dd4a0d42a0ec35b/files/2020-09-06-0320/stagedata.csv - ステージ面積2:https://stat.ink/api-info/stage2 - ブキ:https://stat.ink/api-info/weapon2 | # ライブラリのインポート
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
import seaborn as sns
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings('i... | _____no_output_____ | MIT | program/lightGBM_base_v0.1.ipynb | tomokoochi/splatoon_competition |
データの確認 | def inspection_datas(df):
print('######################################')
print('①サイズ(行数、列数)の確認')
print(df.shape)
print('######################################')
print('②最初の5行の表示')
display(df.head())
print('######################################')
print('③各行のデータ型の確認(オブジェクト型の有無)')
dis... | ######################################
①サイズ(行数、列数)の確認
(66125, 32)
######################################
②最初の5行の表示
| MIT | program/lightGBM_base_v0.1.ipynb | tomokoochi/splatoon_competition |
外部データの結合 | # 外部データの読込
# stage,stage2は若干面積が異なる、バージョンによる違いや計算方法による誤差
stage = pd.read_csv('../gaibu_data/stagedata.csv')
stage2 = pd.read_json('../gaibu_data/stage.json')
weapon = pd.read_csv('../gaibu_data/statink-weapon2.csv')
stage.head(3)
stage2.head(3)
weapon.head(3) | _____no_output_____ | MIT | program/lightGBM_base_v0.1.ipynb | tomokoochi/splatoon_competition |
stageを結合 | # 表記揺れの確認
print(np.sort(train['stage'].unique()))
print(np.sort(test['stage'].unique()))
print(np.sort(stage['stage'].unique()))
# 結合のため列名変更
stage_r = stage.rename(columns = {'size':'stage_size1'})
# 結合
train_s = pd.merge(train, stage_r, on = 'stage', how = 'left')
test_s = pd.merge(test, stage_r, on = 'stage', how = '... | stage_size1 0
dtype: int64
stage_size1 0
dtype: int64
| MIT | program/lightGBM_base_v0.1.ipynb | tomokoochi/splatoon_competition |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.