神经网络馈电时的数值误差

时间:2017-11-01 20:12:53

标签: python tensorflow neural-network

我编写了一个多层神经网络但我在将维度输入其中时遇到错误。我收到了价值错误。

以下是代码:

import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn import metrics
from sklearn import model_selection
from sklearn import preprocessing


# In[207]:

df =pd.read_csv("train_data.csv")


# In[252]:

target = df["target"]
feat=df.drop(['target','connection_id'],axis=1)
target[189]


# In[209]:

len(feature.columns)



# In[210]:

logs_path="Server_attack"


# In[211]:

#Hyperparameters
batch_size=100
learning_rate=0.5
training_epochs=10


# In[244]:

X=tf.placeholder(tf.float32,[None,41])
Y_=tf.placeholder(tf.float32,[None,3])
lr=tf.placeholder(tf.float32)


# In[245]:

#5Layer Neural Network
L=200
M=100
N=60
O=30


# In[257]:

#Weights and Biases
W1=tf.Variable(tf.truncated_normal([41,L],stddev=0.1))
B1=tf.Variable(tf.ones([L]))
W2=tf.Variable(tf.truncated_normal([L,M],stddev=0.1))
B2=tf.Variable(tf.ones([M]))
W3=tf.Variable(tf.truncated_normal([M,N],stddev=0.1))
B3=tf.Variable(tf.ones([N]))
W4=tf.Variable(tf.truncated_normal([N,O],stddev=0.1))
B4=tf.Variable(tf.ones([O]))
W5=tf.Variable(tf.truncated_normal([O,3],stddev=0.1))
B5=tf.Variable(tf.ones([3]))               



# In[247]:

Y1=tf.nn.relu(tf.matmul(X,W1)+B1)
Y2=tf.nn.relu(tf.matmul(Y1,W2)+B2)
Y3=tf.nn.relu(tf.matmul(Y2,W3)+B3)
Y4=tf.nn.relu(tf.matmul(Y3,W4)+B4)
Ylogits=tf.nn.relu(tf.matmul(Y4,W5)+B5)
Y=tf.nn.softmax(Ylogits)


# In[216]:

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Ylogits,labels=Y_)
cross_entropy = tf.reduce_mean(cross_entropy)


# In[217]:

correct_prediction=tf.equal(tf.argmax(Y,1),tf.argmax(Y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


# In[218]:

train_step=tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)


# In[219]:

#TensorBoard Parameters
tf.summary.scalar("cost",cross_entropy)
tf.summary.scalar("accuracy",accuracy)
summary_op=tf.summary.merge_all()


# In[220]:

init = tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)


# In[253]:

with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter(logs_path,graph=tf.get_default_graph())
    for epoch in range(training_epochs):
        batch_count=int(len(feature)/batch_size)
        for i in range(batch_count):


            batch_x,batch_y=feature.iloc[i, :].values.tolist(),target[i]

            _,summary = sess.run([train_step,summary_op],
                                 {X:batch_x,Y:batch_y,learning_rate:0.001}
                                )

我收到以下错误:

ValueError: Cannot feed value of shape (41,) for Tensor 'Placeholder_24:0', which has shape '(?, 41)'

我想重塑一下。

2 个答案:

答案 0 :(得分:0)

您的数据格式与定义为

的占位符不兼容
X=tf.placeholder(tf.float32,[None,41])

重新格式化您在培训/评估期间提供的数据可能更容易。我不知道你导入它的位置,但你需要重塑或交换轴,使其具有格式(索引,41)而不是(41,索引)

答案 1 :(得分:0)

你是对的,你只需要重塑你的输入值,以使它们与占位符的形状兼容。

您的占位符的形状(?,41)表示任何批量大小,包含41个值。相反,您的输入的形状为41

很明显,缺少批量维度。只需在输入中添加1维,就可以了:

batch_x = np.expand_dims(np.array(feature.iloc[i, :].values.tolist()), axis=0)

请注意,您可能还需要为batch_y变量添加1维。 (出于同样的原因)