![]() | ![]() | ![]() | ![]() |
import tensorflow as tf
import numpy as np
Tensörler, tek tip tipte ( dtype
olarak adlandırılır) çok boyutlu dizilerdir. Desteklenen tüm dtypes
adresinde tf.dtypes.DType
.
NumPy hakkında bilginiz varsa, tensörler (bir tür) np.arrays
.
Tüm tensörler Python sayıları ve dizgileri gibi değişmezdir: Bir tensörün içeriğini asla güncelleyemezsiniz, yalnızca yeni bir tane oluşturabilirsiniz.
temel bilgiler
Bazı temel tensörler oluşturalım.
İşte bir "skaler" veya "rank-0" tensörü. Bir skaler tek bir değer içerir ve "eksen" içermez.
# This will be an int32 tensor by default; see "dtypes" below.
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
tf.Tensor(4, shape=(), dtype=int32)
Bir "vektör" veya "sıra-1" tensörü, bir değerler listesi gibidir. Bir vektörün bir ekseni vardır:
# Let's make this a float tensor.
rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
print(rank_1_tensor)
tf.Tensor([2. 3. 4.], shape=(3,), dtype=float32)
Bir "matris" veya "sıra-2" tensörünün iki ekseni vardır:
# If you want to be specific, you can set the dtype (see below) at creation time
rank_2_tensor = tf.constant([[1, 2],
[3, 4],
[5, 6]], dtype=tf.float16)
print(rank_2_tensor)
tf.Tensor( [[1. 2.] [3. 4.] [5. 6.]], shape=(3, 2), dtype=float16)
Bir skaler, şekil: [] | Bir vektör, şekil: [3] | Bir matris, şekil: [3, 2] |
---|---|---|
![]() | ![]() | ![]() |
Tensörlerin daha fazla ekseni olabilir; işte üç eksenli bir tensör:
# There can be an arbitrary number of
# axes (sometimes called "dimensions")
rank_3_tensor = tf.constant([
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]],])
print(rank_3_tensor)
tf.Tensor( [[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]] [[20 21 22 23 24] [25 26 27 28 29]]], shape=(3, 2, 5), dtype=int32)
İkiden fazla ekseni olan bir tensörü görselleştirmenin birçok yolu vardır.
3 eksenli bir tensör, şekil: [3, 2, 5] | ||
---|---|---|
![]() | ![]() | ![]() |
Bir tensörü np.array
veya tensor.numpy
yöntemini kullanarak NumPy dizisine dönüştürebilirsiniz:
np.array(rank_2_tensor)
array([[1., 2.], [3., 4.], [5., 6.]], dtype=float16)
rank_2_tensor.numpy()
array([[1., 2.], [3., 4.], [5., 6.]], dtype=float16)
Tensörler genellikle kayan noktalar ve int'ler içerir, ancak aşağıdakiler de dahil olmak üzere birçok başka türü vardır:
- Karışık sayılar
- Teller
Temel tf.Tensor
sınıfı, tensörlerin "dikdörtgen" olmasını gerektirir --- yani, her eksen boyunca her öğe aynı boyuttadır. Bununla birlikte, farklı şekilleri işleyebilen özel tensör türleri vardır:
- Düzensiz tensörler (aşağıdaki RaggedTensor'a bakın)
- Seyrek tensörler (aşağıdaki SparseTensor'a bakın)
Toplama, eleman bazında çarpma ve matris çarpması dahil olmak üzere tensörler üzerinde temel matematik yapabilirsiniz.
a = tf.constant([[1, 2],
[3, 4]])
b = tf.constant([[1, 1],
[1, 1]]) # Could have also said `tf.ones([2,2])`
print(tf.add(a, b), "\n")
print(tf.multiply(a, b), "\n")
print(tf.matmul(a, b), "\n")
tf.Tensor( [[2 3] [4 5]], shape=(2, 2), dtype=int32) tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int32) tf.Tensor( [[3 3] [7 7]], shape=(2, 2), dtype=int32)
print(a + b, "\n") # element-wise addition
print(a * b, "\n") # element-wise multiplication
print(a @ b, "\n") # matrix multiplication
tf.Tensor( [[2 3] [4 5]], shape=(2, 2), dtype=int32) tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int32) tf.Tensor( [[3 3] [7 7]], shape=(2, 2), dtype=int32)
Her türlü işlemde (ops) tensörler kullanılır.
c = tf.constant([[4.0, 5.0], [10.0, 1.0]])
# Find the largest value
print(tf.reduce_max(c))
# Find the index of the largest value
print(tf.argmax(c))
# Compute the softmax
print(tf.nn.softmax(c))
tf.Tensor(10.0, shape=(), dtype=float32) tf.Tensor([1 0], shape=(2,), dtype=int64) tf.Tensor( [[2.6894143e-01 7.3105854e-01] [9.9987662e-01 1.2339458e-04]], shape=(2, 2), dtype=float32)
şekiller hakkında
Tensörlerin şekilleri vardır. Bazı kelime dağarcığı:
- Şekil : Bir tensörün her bir ekseninin uzunluğu (eleman sayısı).
- Sıra : Tensör eksenlerinin sayısı. Bir skaler rank 0'a, bir vektör rank 1'e, bir matris rank 2'ye sahiptir.
- Eksen veya Boyut : Bir tensörün belirli bir boyutu.
- Boyut : Tensördeki toplam öğe sayısı, çarpım şekli vektörü.
Tensörler ve tf.TensorShape
nesneleri, bunlara erişmek için uygun özelliklere sahiptir:
rank_4_tensor = tf.zeros([3, 2, 4, 5])
Sıra-4 tensörü, şekil: [3, 2, 4, 5] | |
---|---|
![]() | ![]() |
print("Type of every element:", rank_4_tensor.dtype)
print("Number of axes:", rank_4_tensor.ndim)
print("Shape of tensor:", rank_4_tensor.shape)
print("Elements along axis 0 of tensor:", rank_4_tensor.shape[0])
print("Elements along the last axis of tensor:", rank_4_tensor.shape[-1])
print("Total number of elements (3*2*4*5): ", tf.size(rank_4_tensor).numpy())
Type of every element: <dtype: 'float32'> Number of axes: 4 Shape of tensor: (3, 2, 4, 5) Elements along axis 0 of tensor: 3 Elements along the last axis of tensor: 5 Total number of elements (3*2*4*5): 120
Eksenler genellikle endeksleriyle anılırken, her birinin anlamını her zaman takip etmelisiniz. Eksenler genellikle globalden yerele doğru sıralanır: Önce toplu eksen, ardından uzamsal boyutlar ve her konum için özellikler en son gelir. Bu şekilde özellik vektörleri bitişik hafıza bölgeleridir.
Tipik eksen sırası |
---|
![]() |
indeksleme
Tek eksenli indeksleme
TensorFlow, Python'da bir listeyi veya bir dizgiyi indekslemeye benzer standart Python indeksleme kurallarını ve NumPy indeksleme için temel kuralları takip eder.
- indeksler
0
başlar - Negatif endeksler sondan geriye doğru sayılır
- iki nokta üst üste,
:
, dilimler için kullanılır:start:stop:step
rank_1_tensor = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
print(rank_1_tensor.numpy())
[ 0 1 1 2 3 5 8 13 21 34]
Bir skaler ile indeksleme, ekseni kaldırır:
print("First:", rank_1_tensor[0].numpy())
print("Second:", rank_1_tensor[1].numpy())
print("Last:", rank_1_tensor[-1].numpy())
First: 0 Second: 1 Last: 34
Bir :
dilim ile indeksleme, ekseni korur:
print("Everything:", rank_1_tensor[:].numpy())
print("Before 4:", rank_1_tensor[:4].numpy())
print("From 4 to the end:", rank_1_tensor[4:].numpy())
print("From 2, before 7:", rank_1_tensor[2:7].numpy())
print("Every other item:", rank_1_tensor[::2].numpy())
print("Reversed:", rank_1_tensor[::-1].numpy())
Everything: [ 0 1 1 2 3 5 8 13 21 34] Before 4: [0 1 1 2] From 4 to the end: [ 3 5 8 13 21 34] From 2, before 7: [1 2 3 5 8] Every other item: [ 0 1 3 8 21] Reversed: [34 21 13 8 5 3 2 1 1 0]
Çok eksenli indeksleme
Daha yüksek dereceli tensörler, çoklu indeksler geçirilerek indekslenir.
Tek eksen durumundakiyle tamamen aynı kurallar her eksen için bağımsız olarak geçerlidir.
print(rank_2_tensor.numpy())
[[1. 2.] [3. 4.] [5. 6.]]
Her dizin için bir tamsayı ileterek, sonuç bir skalerdir.
# Pull out a single value from a 2-rank tensor
print(rank_2_tensor[1, 1].numpy())
4.0
Herhangi bir tam sayı ve dilim kombinasyonunu kullanarak indeksleyebilirsiniz:
# Get row and column tensors
print("Second row:", rank_2_tensor[1, :].numpy())
print("Second column:", rank_2_tensor[:, 1].numpy())
print("Last row:", rank_2_tensor[-1, :].numpy())
print("First item in last column:", rank_2_tensor[0, -1].numpy())
print("Skip the first row:")
print(rank_2_tensor[1:, :].numpy(), "\n")
Second row: [3. 4.] Second column: [2. 4. 6.] Last row: [5. 6.] First item in last column: 2.0 Skip the first row: [[3. 4.] [5. 6.]]
İşte 3 eksenli tensörlü bir örnek:
print(rank_3_tensor[:, :, 4])
tf.Tensor( [[ 4 9] [14 19] [24 29]], shape=(3, 2), dtype=int32)
Partideki her örnekte tüm konumlarda son özelliği seçme | |
---|---|
![]() | ![]() |
Tensörlerinizdeki tek tek öğeleri işlemek için indekslemeyi nasıl uygulayabileceğinizi öğrenmek için tensör dilimleme kılavuzunu okuyun.
Şekilleri Manipüle Etme
Bir tensörü yeniden şekillendirmek çok faydalıdır.
# Shape returns a `TensorShape` object that shows the size along each axis
x = tf.constant([[1], [2], [3]])
print(x.shape)
(3, 1)
# You can convert this object into a Python list, too
print(x.shape.as_list())
[3, 1]
Bir tensörü yeni bir şekle yeniden şekillendirebilirsiniz. Temel verilerin çoğaltılması gerekmediğinden tf.reshape
işlemi hızlı ve ucuzdur.
# You can reshape a tensor to a new shape.
# Note that you're passing in a list
reshaped = tf.reshape(x, [1, 3])
print(x.shape)
print(reshaped.shape)
(3, 1) (1, 3)
Veriler bellekteki düzenini korur ve aynı verilere işaret eden istenen şekle sahip yeni bir tensör oluşturulur. TensorFlow, en sağdaki dizini artırmanın bellekteki tek bir adıma karşılık geldiği C tarzı "satır-ana" bellek sıralamasını kullanır.
print(rank_3_tensor)
tf.Tensor( [[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]] [[20 21 22 23 24] [25 26 27 28 29]]], shape=(3, 2, 5), dtype=int32)
Bir tensörü düzleştirirseniz, bellekte hangi sırayla düzenlendiğini görebilirsiniz.
# A `-1` passed in the `shape` argument says "Whatever fits".
print(tf.reshape(rank_3_tensor, [-1]))
tf.Tensor( [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29], shape=(30,), dtype=int32)
Tipik olarak tf.reshape
tek makul kullanımı, bitişik eksenleri birleştirmek veya ayırmaktır (veya 1
s eklemek/kaldırmaktır).
Bu 3x2x5 tensör için, dilimler karışmadığından, (3x2)x5 veya 3x(2x5) şeklinde yeniden şekillendirmek mantıklı şeylerdir:
print(tf.reshape(rank_3_tensor, [3*2, 5]), "\n")
print(tf.reshape(rank_3_tensor, [3, -1]))
tf.Tensor( [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24] [25 26 27 28 29]], shape=(6, 5), dtype=int32) tf.Tensor( [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29]], shape=(3, 10), dtype=int32)
Bazı iyi şekiller. | ||
---|---|---|
![]() | ![]() | ![]() |
Yeniden şekillendirme, aynı toplam eleman sayısına sahip herhangi bir yeni şekil için "işe yarayacaktır", ancak eksenlerin sırasına uymazsanız yararlı bir şey yapmayacaktır.
tf.reshape
eksenleri değiştirmek çalışmıyor; Bunun için tf.transpose
ihtiyacınız var.
# Bad examples: don't do this
# You can't reorder axes with reshape.
print(tf.reshape(rank_3_tensor, [2, 3, 5]), "\n")
# This is a mess
print(tf.reshape(rank_3_tensor, [5, 6]), "\n")
# This doesn't work at all
try:
tf.reshape(rank_3_tensor, [7, -1])
except Exception as e:
print(f"{type(e).__name__}: {e}")
tf.Tensor( [[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14]] [[15 16 17 18 19] [20 21 22 23 24] [25 26 27 28 29]]], shape=(2, 3, 5), dtype=int32) tf.Tensor( [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29]], shape=(5, 6), dtype=int32) InvalidArgumentError: Input to reshape is a tensor with 30 values, but the requested shape requires a multiple of 7 [Op:Reshape]
Bazı kötü şekiller. | ||
---|---|---|
![]() | ![]() | ![]() |
Tam olarak belirtilmemiş şekillerle karşılaşabilirsiniz. Ya şekil bir None
içeriyor (bir eksen uzunluğu bilinmiyor) veya tüm şekil None
(tensörün derecesi bilinmiyor).
tf.RaggedTensor dışında, bu tür şekiller yalnızca TensorFlow'un sembolik, grafik oluşturma API'leri bağlamında gerçekleşir:
DTypes
hakkında daha fazlası
Bir tf.Tensor
veri türünü incelemek için Tensor.dtype
özelliğini kullanın.
Bir Python nesnesinden bir tf.Tensor
oluştururken, isteğe bağlı olarak veri tipini belirtebilirsiniz.
Bunu yapmazsanız, TensorFlow verilerinizi temsil edebilecek bir veri türü seçer. TensorFlow, Python tam sayılarını tf.int32
ve Python kayan nokta sayılarını tf.float32
dönüştürür. Aksi takdirde TensorFlow, NumPy'nin dizilere dönüştürürken kullandığı kuralların aynısını kullanır.
Türden türe yayın yapabilirsiniz.
the_f64_tensor = tf.constant([2.2, 3.3, 4.4], dtype=tf.float64)
the_f16_tensor = tf.cast(the_f64_tensor, dtype=tf.float16)
# Now, cast to an uint8 and lose the decimal precision
the_u8_tensor = tf.cast(the_f16_tensor, dtype=tf.uint8)
print(the_u8_tensor)
tf.Tensor([2 3 4], shape=(3,), dtype=uint8)
yayın
Yayın, NumPy'deki eşdeğer özellikten ödünç alınan bir kavramdır. Kısacası, belirli koşullar altında, daha küçük tensörler, üzerlerinde birleşik işlemler yürütülürken daha büyük tensörlere uyacak şekilde otomatik olarak "gerilir".
En basit ve en yaygın durum, bir skalere bir tensör eklemeye veya çarpmaya çalıştığınız zamandır. Bu durumda, skaler diğer argümanla aynı şekilde yayınlanır.
x = tf.constant([1, 2, 3])
y = tf.constant(2)
z = tf.constant([2, 2, 2])
# All of these are the same computation
print(tf.multiply(x, 2))
print(x * y)
print(x * z)
tf.Tensor([2 4 6], shape=(3,), dtype=int32) tf.Tensor([2 4 6], shape=(3,), dtype=int32) tf.Tensor([2 4 6], shape=(3,), dtype=int32)
Benzer şekilde, 1 uzunluğundaki eksenler, diğer argümanlarla eşleşecek şekilde uzatılabilir. Her iki argüman da aynı hesaplamada uzatılabilir.
Bu durumda, 3x1'lik bir matris, 3x4'lük bir matris üretmek için eleman bazında 1x4'lük bir matrisle çarpılır. Baştaki 1'in nasıl isteğe bağlı olduğuna dikkat edin: y'nin şekli [4]
.
# These are the same computations
x = tf.reshape(x,[3,1])
y = tf.range(1, 5)
print(x, "\n")
print(y, "\n")
print(tf.multiply(x, y))
tf.Tensor( [[1] [2] [3]], shape=(3, 1), dtype=int32) tf.Tensor([1 2 3 4], shape=(4,), dtype=int32) tf.Tensor( [[ 1 2 3 4] [ 2 4 6 8] [ 3 6 9 12]], shape=(3, 4), dtype=int32)
Yayınlanan bir ekleme: a [3, 1] çarpı a [1, 4] bir [3,4] verir |
---|
![]() |
İşte yayın olmadan aynı işlem:
x_stretch = tf.constant([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
y_stretch = tf.constant([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
print(x_stretch * y_stretch) # Again, operator overloading
tf.Tensor( [[ 1 2 3 4] [ 2 4 6 8] [ 3 6 9 12]], shape=(3, 4), dtype=int32)
Çoğu zaman, yayın işlemi bellekte genişletilmiş tensörleri asla gerçekleştirmediğinden, yayın hem zaman hem de mekan açısından verimlidir.
tf.broadcast_to
kullanarak yayının nasıl göründüğünü görüyorsunuz.
print(tf.broadcast_to(tf.constant([1, 2, 3]), [3, 3]))
tf.Tensor( [[1 2 3] [1 2 3] [1 2 3]], shape=(3, 3), dtype=int32)
Örneğin, bir matematiksel işlemin aksine, broadcast_to
bellekten tasarruf etmek için özel bir şey yapmaz. Burada tensörü gerçekleştiriyorsunuz.
Daha da karmaşık hale gelebilir. Jake VanderPlas'ın Python Veri Bilimi El Kitabı kitabının bu bölümü daha fazla yayın hilesi gösteriyor (yine NumPy'de).
tf.convert_to_tensor
tf.matmul
ve tf.reshape
gibi çoğu işlem, tf.Tensor
sınıfının argümanlarını alır. Ancak, yukarıdaki durumda fark edeceksiniz, tensör şeklinde Python nesneleri kabul edilir.
Hepsi olmasa da çoğu işlem, tensör olmayan bağımsız değişkenlerde convert_to_tensor
çağırır. Bir dönüştürme kaydı vardır ve NumPy'nin ndarray
, TensorShape
, Python listeleri ve tf.Variable
gibi çoğu nesne sınıfının tümü otomatik olarak dönüştürülür.
Daha fazla ayrıntı için tf.register_tensor_conversion_function
bölümüne bakın ve kendi türünüz varsa otomatik olarak bir tensöre dönüştürmek istersiniz.
Düzensiz Tensörler
Bazı eksenler boyunca değişken sayıda eleman içeren bir tensöre "düzensiz" denir. Düzensiz veriler için tf.ragged.RaggedTensor
kullanın.
Örneğin, Bu normal bir tensör olarak temsil edilemez:
A tf.RaggedTensor , şekil: [4, None] |
---|
![]() |
ragged_list = [
[0, 1, 2, 3],
[4, 5],
[6, 7, 8],
[9]]
try:
tensor = tf.constant(ragged_list)
except Exception as e:
print(f"{type(e).__name__}: {e}")
ValueError: Can't convert non-rectangular Python sequence to Tensor.
Bunun yerine tf.RaggedTensor
kullanarak bir tf.ragged.constant
oluşturun:
ragged_tensor = tf.ragged.constant(ragged_list)
print(ragged_tensor)
<tf.RaggedTensor [[0, 1, 2, 3], [4, 5], [6, 7, 8], [9]]>
Bir tf.RaggedTensor
şekli, bilinmeyen uzunluklara sahip bazı eksenler içerecektir:
print(ragged_tensor.shape)
(4, None)
dize tensörleri
tf.string
bir dtype
, yani verileri tensörlerde dizeler (değişken uzunluklu bayt dizileri) olarak temsil edebileceğinizi söyler.
Dizeler atomiktir ve Python dizeleri gibi dizine eklenemez. Dizinin uzunluğu, tensörün eksenlerinden biri değildir. Bunları işlemek için işlevler için tf.strings
bakın.
İşte bir skaler dize tensörü:
# Tensors can be strings, too here is a scalar string.
scalar_string_tensor = tf.constant("Gray wolf")
print(scalar_string_tensor)
tf.Tensor(b'Gray wolf', shape=(), dtype=string)
Ve bir dizi vektörü:
Bir dizi vektörü, şekil: [3,] |
---|
![]() |
# If you have three string tensors of different lengths, this is OK.
tensor_of_strings = tf.constant(["Gray wolf",
"Quick brown fox",
"Lazy dog"])
# Note that the shape is (3,). The string length is not included.
print(tensor_of_strings)
tf.Tensor([b'Gray wolf' b'Quick brown fox' b'Lazy dog'], shape=(3,), dtype=string)
Yukarıdaki çıktıda b
öneki, tf.string
dtype'ın bir unicode dizesi değil, bir bayt-dizesi olduğunu gösterir. TensorFlow'da unicode metinle çalışma hakkında daha fazla bilgi için Unicode Eğitimi'ne bakın.
Unicode karakterleri iletirseniz, bunlar utf-8 kodludur.
tf.constant("🥳👍")
<tf.Tensor: shape=(), dtype=string, numpy=b'\xf0\x9f\xa5\xb3\xf0\x9f\x91\x8d'>
Dizelere sahip bazı temel işlevler, tf.strings
dahil olmak üzere tf.strings.split
içinde bulunabilir.
# You can use split to split a string into a set of tensors
print(tf.strings.split(scalar_string_tensor, sep=" "))
tf.Tensor([b'Gray' b'wolf'], shape=(2,), dtype=string)
# ...but it turns into a `RaggedTensor` if you split up a tensor of strings,
# as each string might be split into a different number of parts.
print(tf.strings.split(tensor_of_strings))
<tf.RaggedTensor [[b'Gray', b'wolf'], [b'Quick', b'brown', b'fox'], [b'Lazy', b'dog']]>
Üç dize bölünmüş, şekil: [3, None] |
---|
![]() |
Ve tf.string.to_number
:
text = tf.constant("1 10 100")
print(tf.strings.to_number(tf.strings.split(text, " ")))
tf.Tensor([ 1. 10. 100.], shape=(3,), dtype=float32)
Bir dize tensörünü sayılara dönüştürmek için tf.cast
kullanamasanız da, onu baytlara ve ardından sayılara dönüştürebilirsiniz.
byte_strings = tf.strings.bytes_split(tf.constant("Duck"))
byte_ints = tf.io.decode_raw(tf.constant("Duck"), tf.uint8)
print("Byte strings:", byte_strings)
print("Bytes:", byte_ints)
Byte strings: tf.Tensor([b'D' b'u' b'c' b'k'], shape=(4,), dtype=string) Bytes: tf.Tensor([ 68 117 99 107], shape=(4,), dtype=uint8)
# Or split it up as unicode and then decode it
unicode_bytes = tf.constant("アヒル 🦆")
unicode_char_bytes = tf.strings.unicode_split(unicode_bytes, "UTF-8")
unicode_values = tf.strings.unicode_decode(unicode_bytes, "UTF-8")
print("\nUnicode bytes:", unicode_bytes)
print("\nUnicode chars:", unicode_char_bytes)
print("\nUnicode values:", unicode_values)
Unicode bytes: tf.Tensor(b'\xe3\x82\xa2\xe3\x83\x92\xe3\x83\xab \xf0\x9f\xa6\x86', shape=(), dtype=string) Unicode chars: tf.Tensor([b'\xe3\x82\xa2' b'\xe3\x83\x92' b'\xe3\x83\xab' b' ' b'\xf0\x9f\xa6\x86'], shape=(5,), dtype=string) Unicode values: tf.Tensor([ 12450 12498 12523 32 129414], shape=(5,), dtype=int32)
tf.string
dtype, TensorFlow'daki tüm ham bayt verileri için kullanılır. tf.io
modülü, görüntülerin kodunun çözülmesi ve csv'nin ayrıştırılması dahil olmak üzere verileri baytlara ve baytlardan dönüştürmek için işlevler içerir.
seyrek tensörler
Bazen verileriniz çok geniş bir gömme alanı gibi seyrek olur. TensorFlow, seyrek verileri verimli bir şekilde depolamak için tf.sparse.SparseTensor
ve ilgili işlemleri destekler.
A tf.SparseTensor , şekil: [3, 4] |
---|
![]() |
# Sparse tensors store values by index in a memory-efficient manner
sparse_tensor = tf.sparse.SparseTensor(indices=[[0, 0], [1, 2]],
values=[1, 2],
dense_shape=[3, 4])
print(sparse_tensor, "\n")
# You can convert sparse tensors to dense
print(tf.sparse.to_dense(sparse_tensor))
SparseTensor(indices=tf.Tensor( [[0 0] [1 2]], shape=(2, 2), dtype=int64), values=tf.Tensor([1 2], shape=(2,), dtype=int32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64)) tf.Tensor( [[1 0 0 0] [0 0 2 0] [0 0 0 0]], shape=(3, 4), dtype=int32)