【问题标题】:Dumping numpy arrays into neural network将 numpy 数组转储到神经网络中
【发布时间】:2018-06-12 03:18:08
【问题描述】:

我正在尝试使用神经网络解决来自 kaggle 的巨大机器学习挑战。我删除了大部分不相关的数据,并将有用的数据转换为 2D numpy 数组,而将生存数据转换为 1D numpy 数组。由于某种原因,它会抛出一个错误,说两个形状的维度 0 必须相等,我一直在尝试解决它很长一段时间,希望你们能提供帮助。

TensorFlowNumpy.py

import tensorflow as tf

def numpy2tensor(numpy):
    sess = tf.Session()
    with sess.as_default():
        return tf.constant(numpy)

def tensor2numpy(tensor):
    sess = tf.Session()
    with sess.as_default():
        return tensor.eval()

数据集.py

import pandas
import numpy as np
dataset = pandas.read_csv('train.csv')
dataset2= dataset.drop(['PassengerId','Survived','Name','Ticket','Fare','Cabin','Embarked'],axis=1)
dataset3= dataset2.fillna(0)
survive = pandas.read_csv('train.csv')
survival = np.float32(survive.Survived)
dataset4 = np.float32(dataset3)

MainCode.py

import tensorflow as tf
import numpy
from dataset import dataset4,survival
from sklearn.model_selection import train_test_split
from TensorFlowNumpy import numpy2tensor
train_x,test_x,train_y,test_y = train_test_split(dataset4,survival,test_size 
= 0.2)
tensor_train_x = numpy2tensor(train_x)
tensor_train_y = numpy2tensor(train_y)
tensor_test_x = numpy2tensor(test_x)
tensor_test_y = numpy2tensor(test_y)   

n_nodes_hl1 = 10
n_nodes_hl2 = 10
n_classes = 2

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([5, 
n_nodes_hl1])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, 
n_nodes_hl2])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, 
n_classes])),
                    'biases':tf.Variable(tf.random_normal([n_classes]))}


l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), 
hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)
l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), 
hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)
output = tf.matmul(l2,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(logits=prediction, 
labels=tensor_train_y))
     optimizer1 = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

    hm_epochs = 100
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            _, c = sess.run([optimizer1, cost], feed_dict={x:tensor_train_x, 
y:tensor_train_y})
            epoch_loss += c
            print('Epoch', epoch+1, 'completed out 
of',hm_epochs,'loss:',epoch_loss)

         correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))

train_neural_network(tensor_train_x)

【问题讨论】:

  • 错误在哪里,是哪部分代码抛出的?
  • 据此错误不在我的代码中。第一个错误是 tensorflow.python.framework.errors_impl.InvalidArgumentError:两个形状中的维度 0 必须相等,但是对于输入形状为 [712,2]、[ 1,712]。
  • 第二个错误:ValueError:两个形状中的维度 0 必须相等,但对于具有输入形状的“SoftmaxCrossEntropyWithLogits”(操作:“SoftmaxCrossEntropyWithLogits”)为 712 和 1:[712,2]、[1,712 ].

标签: csv numpy tensorflow machine-learning neural-network


【解决方案1】:

我已经多次遇到这个错误,问题显然出在我们的代码中。我今天要离开时没有仔细查看您的代码,但是我闻到您的因变量/输出变量的形状是 [1,712] 应该是 [712,1] 所以代码中的某些地方尝试修复它.基本上它的意思是你有 712 列的一行,但它应该是 712 行和 1 列(输出)。如果有帮助,请将此标记为答案。如果问题仍然存在,请明天联系我。我会看看它。

【讨论】:

  • 我正在尝试使用 DNNclassifier 并重写我的整个代码,我很忙,我会尝试更新您。
猜你喜欢
  • 2019-05-15
  • 2014-01-15
  • 2021-03-09
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
相关资源
最近更新 更多