level 1
import tensorflow as tf
import numpy as np
import pickle
from PIL import Image
import scipy
import matplotlib.pyplot as plt
#下函数将图片转化为矩阵
def imagetomat(filename):
im = np.array(Image.open(filename))
w, d, s = im.shape
data = np.array(im, dtype='float32')
data = np.reshape(data, (1, w * d *s))
return data
xtrain=[]
xtrain=imagetomat("E:\新建文件夹\purepng\pure_0.png")
for i in range(1,20):
x=imagetomat("E:\新建文件夹\purepng\pure_%s.png"%(i))
xtrain=np.row_stack((xtrain,x))
#print(xtrain.shape)
#加上有噪音的碎片图片
n=imagetomat("E:\新建文件夹\\noisee1.bmp")
#print(n.shape)
#print(xtrain.shape)
xtrain=np.row_stack((xtrain,n))
n=imagetomat("E:\新建文件夹\\noisee2.bmp")
xtrain=np.row_stack((xtrain,n))
ytrain=np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2],dtype='int32')
print(xtrain.shape)
print(xtrain.dtype)
print(ytrain.dtype)
print(ytrain.shape)
#构造网络所需要的函数
def weight(shape):
return tf.Variable(tf.random_normal(shape=shape,mean=0,stddev=0.1),dtype='float32')
def biases(shape):
return tf.Variable(tf.constant(0.1,shape=shape),dtype='float32')
#卷积函数
def conv2d(x,W):
return tf.nn.conv2d(input=x,filter=W,strides=[1,1,1,1],padding='SAME')
def max_pool(x):
return tf.nn.max_pool(value=x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#计算准确率(此次数据不够,这一步省略)
#定义输入
ys=tf.placeholder(tf.int32,[None,])
xs=tf.placeholder(tf.float32,[None,20*605*3])/255
#构造网络 第一个卷基层后的宽为10 高位303 第二个后宽为5,高位152
x0=tf.transpose(tf.reshape(xs,[-1,3,20,605]),perm=[0,2,3,1])
W_conv1=weight([5,5,3,20])
b_conv1=biases([20])
a_conv1=conv2d(x0,W_conv1)+b_conv1
z_conv1=tf.nn.relu(a_conv1)
h_conv1=max_pool(z_conv1)
W_conv2=weight([5,5,20,50])
b_conv2=biases([50])
a_conv2=conv2d(h_conv1,W_conv2)+b_conv2
z_conv2=tf.nn.relu(a_conv2)
h_conv2=max_pool(z_conv2)
#接入全连接层
x_conv0=tf.reshape(h_conv2,[-1,5*152*50])
W_fc1=weight([5*152*50,1024])
b_fc1=biases([1024])
a_fc1=tf.matmul(x_conv0,W_fc1)+b_fc1
z_fc1=tf.nn.sigmoid(a_fc1)
W_fc2=weight([1024,2])
b_fc2=biases([2])
a_fc2=tf.matmul(z_fc1,W_fc2)+b_fc2
predict_function=a_fc2
ys_one_hot=tf.one_hot(ys,depth=2)
cost_function=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ys_one_hot,logits=predict_function))
#梯度下降,使得cost——function最小
train_step=tf.train.GradientDescentOptimizer(1e-4).minimize(cost_function)
sess=tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(train_step,feed_dict={xs:xtrain,ys:ytrain})
cost=sess.run(cost_function)
print("cost:%s"%(cost))
sess.close()
2018年11月30日 08点11分