gpt4 book ai didi

pandas - 如何更改 tensorflow 的 numpy 数组的数据类型

转载 作者:行者123 更新时间:2023-11-30 09:19:00 25 4
gpt4 key购买 nike

我正在 tensorflow 中创建一个神经网络,并且我创建了如下占位符:

input_tensor = tf.placeholder(tf.float32, shape = (None,n_input), name = "input_tensor")
output_tensor = tf.placeholder(tf.float32, shape = (None,n_classes), name = "output_tensor")

在训练过程中,我收到以下错误:

Traceback (most recent call last):
File "try.py", line 150, in <module>
sess.run(optimizer, feed_dict={X: x_train[i: i + 1], Y: y_train[i: i + 1]})
TypeError: unhashable type: 'numpy.ndarray'

我发现这是因为 x_train 和 y_train 的数据类型与占位符的数据类型不同。

我的 x_train 看起来有点像这样:

array([[array([[ 1.,  0.,  0.],
[ 0., 1., 0.]])],
[array([[ 0., 1., 0.],
[ 1., 0., 0.]])],
[array([[ 0., 0., 1.],
[ 0., 1., 0.]])]], dtype=object)

它最初是一个像这样的数据框:

0  [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
1 [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]
2 [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]

我做了x_train = train_x.values来获取numpy数组

y_train 看起来是这样的:

array([[ 1.,  0.,  0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])

x_train 的数据类型为 object,y_train 的数据类型为 float64。

我想知道的是如何更改训练数据的数据类型,以便它可以与 tensorflow 占位符很好地配合使用。或者如果我遗漏了什么,请提出建议。

最佳答案

不难猜测您希望数据的形状,但我猜测您可能正在寻找的两种组合之一。我还将尝试在 Pandas 数据框中模拟您的数据。

df = pd.DataFrame([[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]], 
[[[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]],
[[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]]], columns = ['Mydata'])
print(df)

x = df.Mydata.values
print(x.shape)
print(x)
print(x.dtype)

输出:

                               Mydata
0 [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
1 [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]
2 [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]

(3,)
[list([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
list([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0]])
list([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])]
object

组合1

y = [item for sub_list in x for item in sub_list]
y = np.array(y, dtype = np.float32)
print(y.dtype, y.shape)
print(y)

输出:

float32 (6, 3)
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 1. 0.]
[ 1. 0. 0.]
[ 0. 0. 1.]
[ 0. 1. 0.]]

组合2

y = [sub_list for sub_list in x]
y = np.array(y, dtype = np.float32)
print(y.dtype, y.shape)
print(y)

输出:

float32 (3, 2, 3)
[[[ 1. 0. 0.]
[ 0. 1. 0.]]

[[ 0. 1. 0.]
[ 1. 0. 0.]]

[[ 0. 0. 1.]
[ 0. 1. 0.]]]

关于pandas - 如何更改 tensorflow 的 numpy 数组的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46931954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com