我的python版本是3.6.5
CUDA版本为9.0
tensorflow版本为1.9.0
我是初学者。我建立了一个CNN网络并在python shell中运行它。但是它不起作用,也没有错误报告,所以我不知道问题出在哪里。稍后,python shell重新启动。
这是我的代码,希望有人可以帮助我。非常感谢!
import numpy as np
import tensorflow as tf
#ms=readmnist.mnistset()
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
#parameters
learning_rate = 0.01
num_steps = 200
batch_size = 16
display_step = 10
tf.reset_default_graph()
x=tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder(tf.float32,[None,10])
#def of objects
class NN:
def __init__(self):
self.W={}
self.b={}
self.layer={}
self.n=0
def creatNN(self,x,inputsize,outputsize):
self.W[self.n]=tf.Variable(tf.random_normal([inputsize,outputsize],mean=0.0,stddev=0.2))
self.b[self.n]=tf.Variable(tf.random_normal([outputsize],mean=0.0,stddev=0.2))
self.layer[self.n] =tf.add(tf.matmul(x,self.W[self.n]),self.b[self.n])
self.n=self.n+1
return self.layer[self.n-1]
class CNN:
def __init__(self):
self.wc={}
self.bc={}
self.layer={}
self.clayer={}
self.n=0
def creatCNN(self,x,strides=1,k=2,coresize=5,tsize=1,outputsize=32):
self.wc[self.n]=tf.Variable(tf.random_normal([coresize,coresize,tsize,outputsize]))
self.bc[self.n]=tf.Variable(tf.random_normal([outputsize]))
self.layer[self.n]=tf.nn.conv2d(x, self.wc[self.n], strides=[1, strides, strides, 1], padding='SAME')
self.layer[self.n]=tf.nn.bias_add(self.layer[self.n],self.bc[self.n])
self.layer[self.n]=tf.nn.relu(self.layer[self.n])
self.clayer[self.n]=tf.nn.max_pool(self.layer[self.n],ksize=[1,k,k,1],strides=[1,k,k,1],padding='SAME')
self.n=self.n+1
return self.clayer[self.n-1]
x_img = tf.reshape(x, [-1,28,28,1])
'''
construct the network
'''
nn=NN()
cnn=CNN()
cnn1=cnn.creatCNN(x_img,1,2,5,1,32)
cnn2=cnn.creatCNN(cnn1,1,2,5,32,64)
tnn=tf.reshape(cnn2,[-1,7*7*64])
nn1=nn.creatNN(tnn,7*7*64,1024)
nn1=tf.nn.relu(nn1)
output=nn.creatNN(nn1,1024,10)
y=tf.nn.softmax(output)
y=tf.clip_by_value(y, 1e-20, 1)
#train
cross_entropy = -tf.reduce_sum(y_ *tf.log(y))
correct_pred = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
loss=cross_entropy
train_step = tf.train.AdadeltaOptimizer(learning_rate).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#start
for traintime in range(1000):
#trainlab_nextbatch, trainimg_nextbatch = ms.train_nextbatch(batch_size)
trainimg_nextbatch, trainlab_nextbatch = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x:trainimg_nextbatch, y_ :trainlab_nextbatch})
if traintime %200 == 0:
print(sess.run(loss,feed_dict={x:trainimg_nextbatch, y_ :trainlab_nextbatch}))
print(sess.run(accuracy,feed_dict={x:trainimg_nextbatch, y_ :trainlab_nextbatch}))
答案 0 :(得分:0)
我自己完成了这个问题。
我在powershell中而不是python shell中运行此代码,并且得到结果,这意味着我没有cudnn。而且它提醒我,我只为9.2设置了cudnn,而不是9.0,所以我再次设置了cudnn并解决了这个问题。
尽管问题已解决,但我的CNN仍然无法正常工作,我将需要更多时间来升级CNN。