gpt4 book ai didi

python - 索引错误: too many indices for array

转载 作者:行者123 更新时间:2023-11-30 09:51:22 27 4
gpt4 key购买 nike

我最近开始使用 tensorflow ,这就像我的第二段代码,我在设计这个神经网络时陷入困境。我无法增加批量大小,并且这个问题已经持续了很长一段时间。

import numpy as np
import pandas as pd
import tensorflow as tf
import math

#importing the data and preprocessing it

dataset = pd.read_csv('C:\\Users\\Geeks_Sid\\Documents\\Deep-Learning-A-Z\Deep Learning A-Z\\Volume 1 - Supervised Deep Learning\\Part 1 - Artificial Neural Networks (ANN)\\Section 4 - Building an ANN\\Artificial_Neural_Networks\\Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()

#creating a train test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)


# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)


# Creating layers for Neural network

n_nodes_hl1 = 1000
n_nodes_hl2 = 1000
n_nodes_hl3 = 1000
n_classes = 1
batch_size = 50
x = tf.placeholder('float', [None, 11])
y = tf.placeholder('float')

def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([11, 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]))}

hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, 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)

l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)

output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']
print("I was in neural netowrk m")
return output

def train_neural_network(x):
prediction = neural_network_model(x)
# OLD VERSION:
#cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
# NEW:
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
# OLD:
for epoch in range(hm_epochs):
epoch_loss = 0
current = 0
for _ in range(80):
currentprev = current
current += 100
epoch_x, epoch_y = tuple(X_train[:,currentprev:current]) ,tuple(y_train[:,currentprev:current])
_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
epoch_loss += c
print('Epoch', epoch, '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:X_test, y:y_test}))

#sess.run(tf.initialize_all_variables())
# NEW:
sess.run(tf.global_variables_initializer())

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



train_neural_network(x)

我正在处理如下所示的错误。

    train_neural_network(x)
I was in neural netowrk m
Traceback (most recent call last):

File "<ipython-input-8-7c7cbdae9b34>", line 1, in <module>
train_neural_network(x)

File "<ipython-input-7-b7e263fe7976>", line 20, in train_neural_network
epoch_x, epoch_y = tuple(X_train[:,currentprev:current]) ,tuple(y_train[:,currentprev:current])

IndexError: too many indices for array

我正在尝试复制 tensorflow MNIST 数据集分类的代码,其中他们使用了以下代码。我希望您能够将此代码与我的进行比较。如果有任何更正,请帮助我

def train_neural_network(x):
prediction = neural_network_model(x)
# OLD VERSION:
#cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
# NEW:
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
# OLD:
#sess.run(tf.initialize_all_variables())
# NEW:
sess.run(tf.global_variables_initializer())

for epoch in range(hm_epochs):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples/batch_size)):
epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
epoch_loss += c

print('Epoch', epoch, '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:mnist.test.images, y:mnist.test.labels}))

如您所见,我的代码与 MNIST 的代码非常相似,但我无法返回这段代码中的特定元组。

epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})

提前致谢。如果您觉得这个问题重复,我想解释一下,我找不到其他相关问题。

最佳答案

我不太了解您对数据执行的 reshape ,也不了解其原始格式,但这里 y = dataset.iloc[:, 13].values 似乎是y 是一个一维数组,而这里 tuple(y_train[:,currentprev:current] 您像二维矩阵一样访问它,错误告诉您正在使用太多 (2) 个索引无法索引一维数组。

关于python - 索引错误: too many indices for array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596423/

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