我正在尝试使用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')
似乎我正在将(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)'
答案 0 :(得分:0)
Session对象不可调用,为了评估你必须使用session.run
,在你的情况下它会是这样的:
_,accuracy_value = training_session.run([optimizer,
accuracy],feed_dict={x:images28_array, y:labels})
答案 1 :(得分:0)
经过多次试验,结果证明我试图输入的阵列和占位符之间的形状不兼容,我使用以下行转换为灰度,然后展平数组:
images28 = rgb2gray(np.array(images28))
与session.run()函数没有关系,sincce已经被调用了。现在它运行得很好