首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >会话在tensorflow中不可调用

会话在tensorflow中不可调用
EN

Stack Overflow用户
提问于 2018-05-26 02:42:41
回答 2查看 952关注 0票数 0

我正在尝试使用tensorflow运行以下网络来对比利时的交通标志进行分类,除了tensorflow中的run函数之外,一切看起来都很好:

代码语言:javascript
复制
    #!/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)的占位符中,我该如何修复它,错误现在更改为:

代码语言:javascript
复制
ValueError: Cannot feed value of shape (4575, 28, 28, 3) for Tensor 'Placeholder_56:0', which has shape '(?, 28, 28)'
EN

回答 2

Stack Overflow用户

发布于 2018-05-26 05:19:32

Session对象是不可调用的,为了计算,你必须使用session.run,在你的例子中,它应该是这样的:

代码语言:javascript
复制
_,accuracy_value = training_session.run([optimizer,
                   accuracy],feed_dict={x:images28_array, y:labels})
票数 0
EN

Stack Overflow用户

发布于 2018-06-04 05:29:18

经过多次试验,结果是我试图输入的数组和占位符之间的形状不兼容,我在展平数组之前使用以下行转换为灰度:

代码语言:javascript
复制
images28 = rgb2gray(np.array(images28)) 

这与session.run()函数没有关系,因为它已经被调用了。现在它运行得很完美。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50535155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档