Неверный тип dtype для подачи в x-вход заполнителя TensorFlow
Я хочу реализовать простую логистическую регрессию в MNIST с помощью только что установленного TF и хочу отслеживать ход выполнения миниатюрного SGD с TensorBoard.
Я сначала обошелся без тензорной доски, она скомпилирована и получила 0,9166 точность на тестовом наборе.
Однако, когда я добавил тензорную доску, чтобы увидеть, что происходит, я даже не смог ее скомпилировать, я получил:
the placeholders must be fed with dtype float
но все мои массивы являются np-массивами с dtype float!
Если вы можете указать проблемы в моем коде, это было бы удивительно:
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 13:06:44 2016
@author: me
"""
#from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
import os
import random
import numpy as np
from array import array
import struct
import matplotlib.pyplot as plt
import time
#I first placed the decompressed -ubyte files from mnist on the path indicated
os.chdir('/home/me/Bureau/Step1/')
with open("train-labels.idx1-ubyte") as file:
magic, size = struct.unpack(">II",file.read(8))
train_labels_data=np.asarray(array("B",file.read()))
with open("t10k-labels.idx1-ubyte") as file:
magic, size = struct.unpack(">II",file.read(8))
test_labels_data=np.asarray(array("B",file.read()))
with open("train-images.idx3-ubyte") as file:
magic, size, rows, cols =struct.unpack(">IIII",file.read(16))
train_images_data=np.reshape(np.asarray(array("B",file.read())),(size,rows,cols))
with open("t10k-images.idx3-ubyte") as file:
magic, size, rows, cols =struct.unpack(">IIII",file.read(16))
test_images_data=np.reshape(np.asarray(array("B",file.read())),(size,rows,cols))
for i in range(10):
plt.imshow(train_images_data[i,:])
plt.show()
print(train_labels_data[i])
train_images=np.reshape(train_images_data,(60000,28*28)).astype(np.float32)*1/255
test_images=np.reshape(test_images_data,(10000,28*28)).astype(np.float32)*1/255
train_labels=np.zeros((60000,10),dtype=np.float32)
test_labels=np.zeros((10000,10),dtype=np.float32)
for i in range(60000):
a=train_labels_data[i]
train_labels[i,a]=1.
for j in range(10000):
b=test_labels_data[j]
test_labels[j,b]=1.
sess=tf.Session()
x=tf.placeholder(tf.float32, [None, 784],name="x-input")
W=tf.Variable(tf.zeros([784, 10]),name="weights")
b=tf.Variable(tf.zeros([10]),name="bias")
with tf.name_scope("Wx_b") as scope:
y=tf.nn.softmax(tf.matmul(x,W) + b)
w_hist=tf.histogram_summary("weights",W)
b_hist=tf.histogram_summary("bias",b)
y_hist=tf.histogram_summary("y",y)
y_ =tf.placeholder(tf.float32, [None, 10], name="y-input")
with tf.name_scope("xent") as scope:
cross_entropy= -tf.reduce_sum(y_*tf.log(y))
ce_summ=tf.scalar_summary("cross_entropy", cross_entropy)
with tf.name_scope("train") as scope:
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
with tf.name_scope("test") as scope:
correct_prediction =tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
accuracy_summary=tf.scalar_summary("accuracy",accuracy)
merged=tf.merge_all_summaries()
writer=tf.train.SummaryWriter("/tmp/mnist_logs",sess.graph_def)
init=tf.initialize_all_variables()
sess.run(init)
for i in range(1000):
if i % 10 == 0:
feed={x:test_images, y_: test_labels}
result=sess.run([merged, accuracy],feed_dict=feed)
summary_str=result[0]
acc=result[1]
writer.add_summary(summary_str, i)
print("Accuracy at step %s: %s" % (i,acc))
else:
index=np.random.randint(60000-1,size=100)
batch_xs, batch_ys = train_images[index,:], train_labels[index]
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
print(sess.run(accuracy, feed_dict={x: train_images, y_: train_labels}))
Строка, в которой это происходит, находится в канале слияния, однако, так как я кормлю точно так же, как я кормил train_step, я в растерянности
1 ответ
Оказывается, вы не можете запускать один и тот же скрипт снова и снова, когда я снова открыл новый spyder и запустил программу, которая работала!!! Ум = взорван