gpt4 book ai didi

python - tensorflow 错误 : Invalid argument: shape must be a vector

转载 作者:行者123 更新时间:2023-11-28 17:26:18 25 4
gpt4 key购买 nike

我正在使用来自 Kaggle 的泰坦尼克号数据尝试 tensorflow:https://www.kaggle.com/c/titanic

这是我尝试从 Sendex 实现的代码:https://www.youtube.com/watch?v=PwAGxqrXSCs&index=46&list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v#t=398.046664

import tensorflow as tf
import cleanData
import numpy as np

train, test = cleanData.read_and_clean()
train = train[['Pclass', 'Sex', 'Age', 'Fare', 'Child', 'Fam_size', 'Title', 'Mother', 'Survived']]

# one hot
train['Died'] = int('0')
train["Died"][train["Survived"] == 0] = 1

print(train.head())

n_nodes_hl1 = 500
n_classes = 2
batch_size = 100

# tf graph input
x = tf.placeholder("float", [None, 8])
y = tf.placeholder("float")

def neural_network_model(data):

hidden_layer_1 = {'weights':tf.Variable(tf.random_normal([8, n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal(n_nodes_hl1))}

output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes]))}

l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases'])
l1 = tf.nn.relu(l1)

output = tf.matmul(l1, output_layer['weights']) + output_layer['biases']

return output

def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

desired_epochs = 10

with tf.Session() as sess:
sess.run(tf.initialize_all_variables())

for epoch in range(desired_epochs):
epoch_loss = 0
for _ in range(int(train.shape[0])/batch_size):
x_epoch, y_epoch = train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict= {x:x, y:y})
epoch_loss += c
print('Epoch', epoch, 'completed out of', desired_epochs, 'loss:', epoch_loss)

correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Training accuracy:', accuracy.eval({x:x, y:y}))



train_neural_network(x)

当我运行代码时,我收到一条错误消息:“W tensorflow/core/framework/op_kernel.cc:909] 无效参数:shape 必须是 {int32,int64} 的向量,得到 shape []”

有解决办法吗?我在 Github 上看到了一篇关于 tensorflow 代码的帖子,显然该库没有将 pandas 数据框作为输入..

最佳答案

我认为错误在这一行:

    hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([8, n_nodes_hl1])),
'biases': tf.Variable(tf.random_normal(n_nodes_hl1))}

tf.random_normal()shape 参数必须是整数的一维向量(或列表或数组)。对于 'biases' 变量,您将传递一个整数 n_nodes_hl1。修复很简单,只需将该参数包装在一个列表中即可:

    hidden_layer_1 = {...,
'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}

关于python - tensorflow 错误 : Invalid argument: shape must be a vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779654/

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