考慮下面的代碼:
import numpy as np
import tensorflow as tf
simple_data_samples = np.array([
[1, 1, 1, -1, -1],
[2, 2, 2, -2, -2],
[3, 3, 3, -3, -3],
[4, 4, 4, -4, -4],
[5, 5, 5, -5, -5],
[6, 6, 6, -6, -6],
[7, 7, 7, -7, -7],
[8, 8, 8, -8, -8],
[9, 9, 9, -9, -9],
[10, 10, 10, -10, -10],
[11, 11, 11, -11, -11],
[12, 12, 12, -12, -12],
])
def timeseries_dataset_multistep_combined(features, label_slice, input_sequence_length, output_sequence_length, batch_size):
feature_ds = tf.keras.preprocessing.timeseries_dataset_from_array(features, None, input_sequence_length output_sequence_length, batch_size=batch_size)
def split_feature_label(x):
x=tf.strings.as_string(x)
return x[:, :input_sequence_length, :], x[:, input_sequence_length:, label_slice]
feature_ds = feature_ds.map(split_feature_label)
return feature_ds
ds = timeseries_dataset_multistep_combined(simple_data_samples, slice(None, None, None), input_sequence_length=4, output_sequence_length=2,
batch_size=1)
def print_dataset(ds):
for inputs, targets in ds:
print("---Batch---")
print("Feature:", inputs.numpy())
print("Label:", targets.numpy())
print("")
print_dataset(ds)
張量流資料集“ds”由輸入和目標組成。現在我想將 tensorflow 資料集轉換為具有以下屬性的 python 串列:
Index Type Size Value
0 str 13 1 2 3 4 5 6
1 str 13 1 2 3 4 5 6
2 str 13 1 2 3 4 5 6
3 str 13 -1 -2 -3 -4 -5 -6
4 str 13 -1 -2 -3 -4 -5 -6
5 str 13 2 3 4 5 6 7
.... and so on
在上面的示例中,我們假設創建了一個包含字串的 python 串列。在“值”欄位中,您可以在左側看到 tensorflow 資料集的輸入(例如 1 2 3 4,字串之間有空格),在右側您可以看到相應的目標(例如 5 6字串之間的空格)。需要注意的是,輸入和目標之間有一個水平制表符“\t”(例如 1 2 3 4.\t5 6.)
我將如何編碼?
uj5u.com熱心網友回復:
如果你想要一個pandas資料框,你可以嘗試這樣的事情:
import numpy as np
import pandas as pd
features = np.concatenate(list(ds.map(lambda x, y: tf.transpose(tf.squeeze(x, axis=0)))))
targets = np.concatenate(list(ds.map(lambda x, y: tf.transpose(tf.squeeze(y, axis=0)))))
values = list(map(lambda x: x[0] "\t" x[1], zip([" ".join(item) for item in features.astype(str)],
[" ".join(item) for item in targets.astype(str)])))
types = [type(v).__name__ for v in values]
sizes = [len(v) for v in values]
df = pd.DataFrame({'Size':sizes, 'Type':types, 'Value':values})
df.index.name = 'Index'
print(df.head())
uj5u.com熱心網友回復:
我使用了你的 print_dataset 函式。
def print_dataset(ds):
list_sets = []
for input, targets in ds:
input = np.transpose(np.array(inputs)[0])
label = np.transpose(np.array(targets)[0])
for input_set, label_set in zip(input, label):
set = ""
set = "".join(str(value).replace("b'", "").replace("'", "") " " for value in input_set)
set = "\t" # add the tab
set = "".join(str(value).replace("b'", "").replace("'", "") " " for value in label_set)
set = set[:-1] # remove the trailing white space
# print(set) #prints each line individually
list_sets.append(set)
print(list_sets) # prints the whole list
如果您列印每行都可以正常作業,請忽略您可以看到“\t”而不是帶有空格的制表符。Python 僅列印“\t”以通過用快捷方式替換無用空間來縮短長度。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/415555.html
標籤:
