Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python MNIST tensorflow-无法找出问题所在_Python_Tensorflow - Fatal编程技术网

Python MNIST tensorflow-无法找出问题所在

Python MNIST tensorflow-无法找出问题所在,python,tensorflow,Python,Tensorflow,我一直在试图弄明白为什么这几个小时都不起作用,但我一事无成。非常感谢你的帮助 它基本上是tensorflow网站上的教程的副本,对使用本地数据集做了一些调整。但我只有10%的准确率,这和猜测是一样的 import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import tensorflow as tf df = pd.read_csv('train.csv') yi

我一直在试图弄明白为什么这几个小时都不起作用,但我一事无成。非常感谢你的帮助

它基本上是tensorflow网站上的教程的副本,对使用本地数据集做了一些调整。但我只有10%的准确率,这和猜测是一样的

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf

df = pd.read_csv('train.csv')
yi = df['label']
df = df.drop('label',1)

labels=[]
for i in range(len(yi)):
    #convert to one hot 
    label = [0,0,0,0,0,0,0,0,0,0]
    label[yi[i]]= 1
    labels.append(label)

labels = np.array(labels)
df = df.as_matrix()

df_train, df_test, y_train, y_test = train_test_split(df,labels)




x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder('float', [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)



sess = tf.Session()

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

def next_batch(num, data, labels):

    #get batches for training 

    idx = np.arange(0 , len(data))
    np.random.shuffle(idx)
    idx = idx[:num]
    data_shuffle = [data[ i] for i in idx]
    labels_shuffle = [labels[ i] for i in idx]

    return np.asarray(data_shuffle), np.asarray(labels_shuffle)

for _ in range(1000):
    df_train0, y_train0 = next_batch(100, df_train, y_train)
    sess.run(train_step, feed_dict={ x: df_train0, y_: y_train0})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
print(sess.run(accuracy, feed_dict={x:df_test, y_:y_test}))

您的问题是,您正在用0s初始化W,因此没有要修改的渐变,所有的logit都将是0s

W = tf.Variable(tf.zeros([784, 10]))
您应该随机初始化它以打破对称性

W = tf.Variable(tf.random_normal([784, 10]))

编辑:无需随机化,因为目标logit将破坏对称性。然而,如果有一个隐藏层,这将是必要的。真正的问题似乎在于投入的规模。除以255应该可以解决这个问题。

你的问题是你正在用0初始化W,因此没有梯度可以修改,所有的logit都是0

W = tf.Variable(tf.zeros([784, 10]))
您应该随机初始化它以打破对称性

W = tf.Variable(tf.random_normal([784, 10]))

编辑:无需随机化,因为目标logit将破坏对称性。然而,如果有一个隐藏层,这将是必要的。真正的问题似乎在于投入的规模。除以255应该可以解决这个问题。

我不知道为什么这有助于提高准确性,所以如果有人能给出更好的答案,请回答

我改变了:

y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
将是:

y = tf.matmul(x, W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
完整代码示例:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
import tensorflow as tf
from scipy.stats import entropy

def next_batch(num, data, labels):
  '''get batches for training'''

  idx = np.arange(0 , len(data))
  np.random.shuffle(idx)
  idx = idx[:num]
  data_shuffle = [data[ i] for i in idx]
  labels_shuffle = [labels[ i] for i in idx]

  return np.asarray(data_shuffle), np.asarray(labels_shuffle)

df = pd.read_csv('train.csv')
df_X = df.iloc[:, 1:]
df_y = df['label']

y_one_hot = MultiLabelBinarizer().fit_transform(df_y.values.reshape(-1, 1))

df_train, df_test, y_train, y_test = train_test_split(df_X.values, y_one_hot)

x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder('float', [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)

sess = tf.Session()

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

for _ in range(1000):
  df_train0, y_train0 = next_batch(100, df_train, y_train)
  sess.run(train_step, feed_dict={ x: df_train0, y_: y_train0})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
print(sess.run(accuracy, feed_dict={x:df_test, y_:y_test}))

结果准确率:大约
0.88

我不知道为什么这有助于提高准确率,所以如果有人能给出更好的答案,请回答

我改变了:

y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
将是:

y = tf.matmul(x, W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
完整代码示例:

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
import tensorflow as tf
from scipy.stats import entropy

def next_batch(num, data, labels):
  '''get batches for training'''

  idx = np.arange(0 , len(data))
  np.random.shuffle(idx)
  idx = idx[:num]
  data_shuffle = [data[ i] for i in idx]
  labels_shuffle = [labels[ i] for i in idx]

  return np.asarray(data_shuffle), np.asarray(labels_shuffle)

df = pd.read_csv('train.csv')
df_X = df.iloc[:, 1:]
df_y = df['label']

y_one_hot = MultiLabelBinarizer().fit_transform(df_y.values.reshape(-1, 1))

df_train, df_test, y_train, y_test = train_test_split(df_X.values, y_one_hot)

x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder('float', [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)

sess = tf.Session()

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

for _ in range(1000):
  df_train0, y_train0 = next_batch(100, df_train, y_train)
  sess.run(train_step, feed_dict={ x: df_train0, y_: y_train0})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
print(sess.run(accuracy, feed_dict={x:df_test, y_:y_test}))


结果精度:大约
0.88

您没有使用任何隐藏层吗?这只是一个线性模型吗?你估计准确率是多少?我估计至少90。我知道还有很多层我可以添加,但需要先让它工作!如果没有对培训数据的访问权限,则无法运行此程序并尝试调试。你能上传你运行这个的数据文件吗?我从你没有使用任何隐藏层的表格中得到的?这只是一个线性模型吗?你估计准确率是多少?我估计至少90。我知道还有很多层我可以添加,但需要先让它工作!如果没有对培训数据的访问权限,则无法运行此程序并尝试调试。你能上传你运行这个的数据文件吗?我从表格中得到,我认为梯度是熵方程的梯度,而不是回归。这两种方法都没有帮助。梯度被反向传播到W变量。您还需要缩小输入的比例并将其居中,例如除以255。@ManoloSantos如果用零初始化权重是个问题,为什么官方教程会说“既然我们要学习W和b,它们最初是什么并不重要。”?@Jarad,您是对的。起初我以为有一个隐藏层。在这种情况下,需要通过随机初始化权重来打破对称性。真正的问题是输入的规模,将它们除以255,它就会起作用。我已经更新了我的答案。为什么它不能处理未标度的输入?我认为梯度是熵方程的梯度,而不是回归。这两种方法都没有帮助。梯度被反向传播到W变量。您还需要缩小输入的比例并将其居中,例如除以255。@ManoloSantos如果用零初始化权重是个问题,为什么官方教程会说“既然我们要学习W和b,它们最初是什么并不重要。”?@Jarad,您是对的。起初我以为有一个隐藏层。在这种情况下,需要通过随机初始化权重来打破对称性。真正的问题是输入的规模,将它们除以255,它就会起作用。我已经更新了我的答案。为什么它不能处理未标度的输入?原始版本的问题是
tf.log(大数值)
is
inf
。因此,它是不稳定的。第二个版本防止了这种情况,缩小了登录以避免这种不稳定性。更正:实际上,为了防止这种不稳定性,第二个版本使用了标识
log(e^x)==x
。原始版本的问题是
tf.log(big_number)
inf
。因此,它是不稳定的。第二个版本防止了这种情况,缩小了logit以避免这种不稳定性。更正:实际上,为了防止这种不稳定性,第二个版本使用identity
log(e^x)=x