tensorflow - 会话在张量流中不可调用
问题描述
我正在尝试使用 tensorflow 运行以下网络来对比利时交通标志进行分类,除了 tensorflow 中的运行功能外,一切看起来都很好:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 15:56:32 2018
@author: raed
"""
import tensorflow as tf
import os
import skimage.io
from skimage import transform
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#config=tf.ConfigProto(log_device_placement=True)
#config_soft = tf.ConfigProto(allow_soft_placement =True)
def load_data(data_directory):
directories = [d for d in os.listdir(data_directory)
if os.path.isdir(os.path.join(data_directory, d))]
labels = []
images = []
for d in directories:
label_directory = os.path.join(data_directory, d)
file_names = [os.path.join(label_directory, f)
for f in os.listdir(label_directory)
if f.endswith(".ppm")]
for f in file_names:
images.append(skimage.io.imread(f))
labels.append(int(d))
return images, labels
Root_Path = "/home/raed/Dropbox/Thesis/Codes/Tensorflow"
training_Directory = os.path.join(Root_Path,"Training")
testing_Directory = os.path.join(Root_Path,"Testing")
images, labels = load_data(training_Directory)
# Convert lists to array in order to facilitate information retrieval
images_array = np.asarray(images)
labels_array = np.asanyarray(labels)
#print some information about the datasets
print('Images Array Dimensions :',images_array.ndim)
print('Images Array length :',images_array.size)
print('Labels Dimensions :', labels_array.ndim)
print('Labels Size in Bytes :',labels_array.nbytes)
print('Number of labels :',len(labels_array))
print(images_array[0])
# plotting the distribution of different signs
sns.set(palette="deep")
plt.hist(labels,62)
plt.show()
# Selecting couple of images based on their indices
traffic_signs = [300,2250,3650,4000]
for i in range(len(traffic_signs)):
plt.subplot(1, 4, i+1)
plt.imshow(images_array[traffic_signs[i]])
plt.show()
# Fill out the subplots with the random images and add shape, min and max values
for i in range(len(traffic_signs)):
plt.subplot(1,4,i+1)
plt.imshow(images_array[traffic_signs[i]])
plt.axis('off')
plt.show()
print("Shape:{0},max:{1}, min:{2}".format(images_array[traffic_signs[i]].shape,
images_array[traffic_signs[i]].max(),
images_array[traffic_signs[i]].min()))
# Get unique labels
unique_labels = set(labels_array)
# initialize the figure
plt.figure(figsize=(15,15))
i=1
for label in unique_labels:
image = images_array[labels.index(label)]
plt.subplot(8,8,i)
plt.axis('off')
plt.title('label:{0} ({1})'.format(label, labels.count(label)))
i=i+1
plt.imshow(image)
plt.show()
images28 = [transform.resize(image, (28, 28)) for image in images]
for i in range(len(traffic_signs)):
plt.subplot(1,4,i+1)
plt.imshow(images_array[traffic_signs[i]])
plt.axis('off')
plt.show()
print("Shape:{0},max:{1}, min:{2}".format(images28[i].shape,
images28[i].max(),
images28[i].min()))
#convert to grayscale
images28 = np.array(images28)
gray_images = skimage.color.rgb2gray(images28)
for i in range(len(traffic_signs)):
plt.subplot(1, 4, i+1)
plt.axis('off')
plt.imshow(gray_images[traffic_signs[i]], cmap="gray")
plt.subplots_adjust(wspace=0.5)
# Show the plot
plt.show()
# Modeling the neural network using TensorFlow
# prepare placeholders
x = tf.placeholder(dtype=tf.float32, shape =[None, 28 ,28])
y = tf.placeholder(dtype= tf.int32, shape=[None])
#Flatten the input data
images_flat = tf.layers.flatten(x)
##Fully connected layer , Multi-layer Perceptron (MLP)
logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)
#Define loss function
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=logits))
#define an optimizer (Stochastic Gradient Descent )
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
#convert logits to label indices
correct_prediction = tf.arg_max(logits,1)
#define an accuracy metric
accuracy =tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#########################################
print('######### Main Program #########')
#########################################
print("images_flat: ", images_flat)
print("logits: ", logits)
print("loss: ", loss)
print("Optimizer:",optimizer)
print("predicted_labels: ", correct_prediction)
#images28 = np.asanyarray(images28).reshape(images28.shape[0],images28.shape[1],images28.shape[2])
# set the seed
tf.set_random_seed(1234)
# initialize the session in Tensorflow
first_session = tf.Session()
first_session.run(tf.global_variables_initializer())
#
for i in range(len(images28)):
print('Epoch', i)
_, accuracy = first_session.run([optimizer, accuracy], feed_dict={x:images28 , y:labels})
if i % 10 ==0:
print("Loss :", loss)
print('Done With Epoch')
first_session.close()
看来我正在将 (4575, 28, 28,3) 数组放入 (?,28,28) 的占位符中,我该如何解决,现在错误更改为以下内容:
ValueError: Cannot feed value of shape (4575, 28, 28, 3) for Tensor 'Placeholder_56:0', which has shape '(?, 28, 28)'
解决方案
经过多次试验,结果是我尝试输入的阵列与占位符之间的形状不兼容,我在展平阵列之前使用以下行转换为灰度:
images28 = rgb2gray(np.array(images28))
与 session.run() 函数没有关系,因为它已经被调用了。现在它运行完美
推荐阅读
- c++ - 通过私有继承覆盖公共别名方法
- swift - 如何区分 Siri Remote 按钮按下和游戏手柄按钮按下?
- java - VisualVM 探查器的行为莫名其妙,我不知所措。这里发生了什么?
- powershell - 将图像存储在 Sharepoint 中并获取要在 PowerBI 上显示的 URL 图像
- javascript - 防止 xmlhttp 函数在 keyup 上再次运行
- database - 如何每天有效地存储 1B 的新行并有可能进行查询/索引?
- jquery - 文件上传不再适用于 Chrome
- html - 如何在引导网格 div 中移动元素
- python - 如何在 Tkinter 的标签内添加变量?
- python - 根据字典值追加列表嵌套字典