# coding=utf8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
#Activation function : don't Know 没卷积没池化,我也不知道为啥,也不敢问
#lost Function : - log(p) 对数损失函数softmax分类
def sigmoid(x,deriv = False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
mnist=input_data.read_data_sets('data/',one_hot=True)
#print
#mnist type是dataSet ,分train,test,validation (训练,测试,验证)
trainimg=mnist.train.images
#print(np.array(trainimg).shape) #np.ndarray ,可以转化为np.array 读
trainlab=mnist.train.labels
testimg = mnist.test.images
testlab = mnist.test.labels
# print("Train image : %s"%(trainimg.shape,))
# print("Train labels: %s"%(trainlab.shape,))
# print("Test image : %s"%(testimg.shape,))
# print("Test labels: %s"%(testlab.shape,))
#plt module
# nsample = 5
# randidx = np.random.randint(trainimg.shape[0],size = nsample)#取五个数,[0,55000)返回一个列表
#print("randint is ")
# for i in randidx:
# curr_img = np.reshape(trainimg[i,:],[28,28]) #
# #print("curr_img is ")
# #print(curr_img)
# curr_lable = np.argmax(trainlab[i,:])
# #print("curr_lable is :")
# #print(curr_lable)
# plt.matshow(curr_img, cmap = plt.get_cmap('gray'))
# plt.title(str(i)+"th Train Data."+ " Label id "+str(curr_lable))
# #print (str(i)+"th Train Data."+ " Label id "+str(curr_lable))
# plt.show()
# plt在上面
x = tf.placeholder('float',[None,784])
y = tf.placeholder('float',[None,10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.zeros([10])
yo = tf.nn.softmax(tf.matmul(x,W)+b) # wx+b = yo
#print("actv is :",yo)
learing_reat = 0.01
cost = tf.reduce_mean(tf.reduce_sum(-y*tf.log(yo),reduction_indices=1)) # - log(p)
optm = tf.train.GradientDescentOptimizer(learing_reat).minimize(cost)
#prediction is correct ?
pred = tf.equal(tf.argmax(yo,1),tf.argmax(y,1))
# Accuracy
accr = tf.reduce_mean(tf.cast(pred,'float'))
# print(accr)
# accr = tf.cast(pred,'float') 错了?
# print(accr)
train_number = 51 #迭代次数
batch_size = 100 #分批次处理
display_step = 5 #显示频率
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(train_number):
avg_cost=0
numbatch = int(mnist.train.num_examples/batch_size) # 批数
for i in range(numbatch):
batch_xs ,batch_ys = mnist.train.next_batch(batch_size)
feeds = {x: batch_xs, y: batch_ys}
sess.run(optm,feed_dict=feeds)
avg_cost += sess.run(cost,feed_dict=feeds)/numbatch
if step % display_step == 0:
feeds_train = {x:batch_xs,y:batch_ys}
feed_test = {x:mnist.test.images,y:mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feeds_train)
test_acc = sess.run(accr, feed_dict = feed_test)
print("Epoch: %03d/%03d cost: %9f train_acc: %3f test_acc: %3f"%(step,train_number,avg_cost,train_acc,test_acc))
sess.close()
萌新微菜,欢迎讨论