mozarts 2018-06-25 11:19 采纳率: 25%
浏览 1300
已结题

TensorFlow卷积神经网络实现,图片与对应标签的拟合。一直显示卡在正在运行。

#python3代码
#TensorFlow卷积神经网络实现,图片与对应标签的拟合
#程序不报错,一直显示正在运行
#请问错在哪里?
#数据集 https://pan.baidu.com/s/1Z7_ULAW3LFrUk4WkHC0s3Q

import os
import numpy as np
from PIL import Image
import tensorflow as tf
import matplotlib.pyplot as plt

#-------------获取数据集,构造批数据:batch-----------------------------------------

def get_files(file_dir):
pictures = []
numbers = []

for file in os.listdir(file_dir): # 7000.jpg
    name = file.split(sep='.')
    pictures.append(file_dir+"\\"+file)
    numbers.append(name[0])

print('There are %d pictures'%(len(pictures)))


temp = np.array([pictures,numbers])
temp = temp.transpose()
np.random.shuffle(temp)

pictures_list = list(temp[:,0])
numbers_list = list(temp[:,1])

#numbers_list = [int(float(i)) for i in numbers_list]

return  pictures_list,numbers_list
#返回两个list

def get_batch(image,label,image_W,image_H,batch_size,capacity): # image = pictures label = numbers
image = tf.cast(image,tf.string)
label = tf.cast(label,tf.int32)
#tf.cast()用来做类型转换

input_queue = tf.train.slice_input_producer([image,label])
#加入队列
label = input_queue[1]

image_contents = tf.read_file(input_queue[0])
image = tf.image.decode_jpeg(image_contents,channels=3)

#jpeg或者jpg格式都用decode_jpeg函数,其他格式可以去查看官方文档

image = tf.image.resize_image_with_crop_or_pad(image,image_W,image_H)
#resize

image = tf.image.per_image_standardization(image)
#对resize后的图片进行标准化处理

image_batch,label_batch = tf.train.batch([image,label],batch_size = batch_size,num_threads=16,capacity = capacity)

label_batch = tf.reshape(label_batch,[batch_size])



return image_batch,label_batch
#获取两个batch,两个batch即为传入神经网络的数据

#-----------卷积神经网络节点,搭建卷积神经网络----------------------------------------------------

def conv_op(input_op,name,kh,kw,n_out,dh,dw):
n_in = input_op.get_shape()[-1].value

with tf.name_scope(name) as scope:
    kernel=tf.get_variable(scope+"w",
        shape=[kh,kw,n_in,n_out],dtype=tf.float32,
        initializer=tf.contrib.layers.xavier_initializer_conv2d())

    conv=tf.nn.conv2d(input_op,kernel,(1,dh,dw,1),padding='SAME')
    bias_init_val=tf.constant(0.0,shape=[n_out],dtype=tf.float32)
    biases=tf.Variable(bias_init_val,trainable=True,name='b')
    z=tf.nn.bias_add(conv,biases)
    activation=tf.nn.relu(z,name=scope)
    return activation

def fc_op(input_op,name,n_out):
n_in=input_op.get_shape()[-1].value

with tf.name_scope(name) as scope:
    kernel = tf.get_variable(scope+"w",shape=[n_in,n_out],
            dtype=tf.float32,
            initializer=tf.contrib.layers.xavier_initializer())
    biases=tf.Variable(tf.constant(0.1,
            shape=[n_out],dtype=tf.float32),name='b')
    activation=tf.nn.relu_layer(input_op,kernel,biases,name=scope)
    return activation

def fc_end_layer(inputs,in_size,out_size,activation_function=None):
Weights=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+0.1)

Wx_plus_b=tf.matmul(inputs,Weights)+biases

if activation_function is None:
    outputs=Wx_plus_b
else:
    outputs=activation_function(Wx_plus_b)
return outputs

def mpool_op(input_op,name,kh,kw,dh,dw):
return tf.nn.max_pool(input_op,ksize=[1,kh,kw,1],
strides=[1,dh,dw,1],padding='SAME',name=name)

def inference_op(input_op,keep_prob):

conv1_1=conv_op(input_op,name="conv1_1",kh=3,kw=3,n_out=64,dh=1,
                dw=1)
conv1_2=conv_op(conv1_1,name="conv1_2",kh=3,kw=3,n_out=64,dh=1,
                dw=1)
pool1=mpool_op(conv1_2,name="pool1",kh=2,kw=2,dw=2,dh=2)


conv2_1=conv_op(pool1,name="conv2_1",kh=3,kw=3,n_out=128,dh=1,
                dw=1)
conv2_2=conv_op(conv2_1,name="conv2_2",kh=3,kw=3,n_out=128,dh=1,
                dw=1)
pool2=mpool_op(conv2_2,name="pool2",kh=2,kw=2,dh=2,dw=2)


conv3_1=conv_op(pool2,name="conv3_1",kh=3,kw=3,n_out=256,dh=1,
                dw=1)
conv3_2=conv_op(conv3_1,name="conv3_2",kh=3,kw=3,n_out=256,dh=1,
                dw=1)
conv3_3=conv_op(conv3_2,name="conv3_3",kh=3,kw=3,n_out=256,dh=1,
                dw=1)
pool3=mpool_op(conv3_3,name="pool3",kh=2,kw=2,dh=2,dw=2)


conv4_1=conv_op(pool3,name="conv4_1",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
conv4_2=conv_op(conv4_1,name="conv4_2",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
conv4_3=conv_op(conv4_2,name="conv4_3",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
pool4=mpool_op(conv4_3,name="pool4",kh=2,kw=2,dh=2,dw=2)


conv5_1=conv_op(pool4,name="conv5_1",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
conv5_2=conv_op(conv5_1,name="conv5_2",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
conv5_3=conv_op(conv5_2,name="conv5_3",kh=3,kw=3,n_out=512,dh=1,
                dw=1)
pool5=mpool_op(conv5_3,name="pool5",kh=2,kw=2,dw=2,dh=2)


shp=pool5.get_shape()
flattened_shape=shp[1].value*shp[2].value*shp[3].value
resh1=tf.reshape(pool5,[-1,flattened_shape],name="resh1")

fc6=fc_op(resh1,name="fc6",n_out=4096)
fc6_drop=tf.nn.dropout(fc6,keep_prob,name="fc6_drop")

fc7=fc_op(fc6_drop,name="fc7",n_out=4096)
fc7_drop=tf.nn.dropout(fc7,keep_prob,name="fc7_drop")

fc8=fc_op(fc7_drop,name="fc8",n_out=1000)
prediction=fc_end_layer(fc8,1000,1,activation_function=None)

return prediction

#---------构造损失节点:loss 优化节点:optimizer 训练节点:train---------------------------------------

x=tf.placeholder(tf.float32,[None,28,28,3])
y=tf.placeholder(tf.float32,[None,1])

prediction = inference_op(x,0.5)

loss = tf.reduce_mean(tf.square(y - prediction))
optimizer = tf.train.GradientDescentOptimizer(0.5)

train = optimizer.minimize(loss)

#--------运行网络--------------------------------------------------

IMG_W = 28
IMG_H = 28
BATCH_SIZE = 4
CAPACITY = 24
MAX_STEP = 100
learning_rate = 0.0005
train_dir = 'D:\VGGNet-16\fatigue_cycle_picture'

pictures_list,numbers_list = get_files(train_dir)
image_batch,label_batch = get_batch(pictures_list,numbers_list,IMG_W,IMG_H,BATCH_SIZE,CAPACITY)
#label_batch=tf.to_float(label_batch)

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

for i in range(100):
print(i)

print(sess.run(image_batch))
sess.run(train,feed_dict={x:image_batch.eval(session=sess),y:label_batch.eval(session=sess)})

sess.close()

  • 写回答

1条回答 默认 最新

  • threenewbee 2018-06-25 15:00
    关注

    通过summary添加日志输出,放到tensorboard里面看下

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊