用的是卷积神经网络CNN,正常的卷积大家应该都有所了解,这里为了提高准确率,针对这个提目加了数据强化的操作,提交kaggle准确率从原来的98.957%达到了99.285%
下面是我的具体代码流程:
import tensorflow as tf
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import math
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator,array_to_img,img_to_array,load_img
#引入数据
file=pd.read_csv('../data/train.csv')
#每个批次的大小
batch_size=50
#初始化权值
def weight_variable(shape,name):
initial=tf.truncated_normal(shape,stddev=0.1)#生成一个截断正态分布
return tf.Variable(initial,name=name)
#初始化偏置
def bias_variable(shape,name):
initial=tf.constant(0.1,shape=shape)
return tf.Variable(initial,name=name)
#卷积层
def conv2d(x,W):
#2d是二维的意思
#x是一个tensor,形状是[batch,in_height,in_width,in_channels]NHWC关系,分别是批次大小(本例batch_size=100),图片高度,图片宽度,通道数(黑白照片是1,彩色是3)
#w是一个滤波器,tensor,形状是[filter_height,filter_width,in_channels,out_channels],滤波器长,宽,输入和输出通道数
#步长参数,strides[0]=strides[3]=1,strides[1]代表x方向的步长,strides[2]代表y方向的步长
#padding:一个字符串,要么是'SAME'要么是'VALID',对应两种卷积方法,前者补零,后者不会超出平面外部
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#池化层
def max_pool_2x2(x):#这里定义的最大池化的方式,他会取2*2窗口里最大的值
#ksize[1,x,y,1]
#ksize是窗口大小,索引0,3对应的值必须是1,因为是2*2,所以索引1,2对应的值为2,步长对应也是2
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#命名空间
with tf.name_scope('input'):
#定义两个占位符
x=tf.placeholder(tf.float32,[None,784],name='x-input')#28*28
y=tf.placeholder(tf.float32,[None,10],name='y-input')
with tf.name_scope('x_image'):
# 改变x的格式,转为4d的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x, [-1, 28, 28, 1],name='x_image') # -1是指个数不确定 1是通道数
with tf.name_scope('Conv1'):
#初始化第一个卷积层的权值和偏置
# 多少个卷积核返回多少个矩阵
with tf.name_scope('W_conv1'):
W_conv1=weight_variable([5,5,1,32],name='W_conv1')#5*5的采样窗口,32个卷积核从1个平面抽取特征 1的意思是通道数,如果是彩色则为3
with tf.name_scope('b_conv1'):
b_conv1=bias_variable([32],name='b_conv1')#每一个卷积核一个偏置值
#把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
with tf.name_scope('conv2d_1'):
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#[?,28,28,32]
with tf.name_scope('h_pool1'):
h_pool1=max_pool_2x2(h_conv1)#进行max—pooling #[?,14,14,32]
with tf.name_scope('Conv2'):
#初始化第二个卷积层的权值和偏置
with tf.name_scope('W_conv2'):
W_conv2=weight_variable([5,5,32,64],name='W_conv2')#5*5的采样窗口,64个卷积核从32个平面抽取特征 因为前面32个卷积核生成了32个平面图。
with tf.name_scope('b_conv2'):
b_conv2=bias_variable([64],name='b_conv2')#每一个卷积核一个偏置值
#把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
with tf.name_scope('conv2d_2'):
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
with tf.name_scope('h_pool2'):
h_pool2=max_pool_2x2(h_conv2)#进行max—pooling
#多少个卷积核返回多少个矩阵(feature map)哈哈
#因为我们用的是SAME,不是VALID,所以会自动填充,所以卷积之后不是24*24而依然是28*28,这样池化后才是14*14
#28*28的图片第一次卷积后还是28*28,第一次池化后变为14*14
#第二次卷积后,还是14*14,第二次池化后,7*7
#通过上面操作后得到64张7*7的平面
with tf.name_scope('fc1'):
with tf.name_scope('W_fc1'):
#初始化第一个全连接层的权值和偏置值
W_fc1=weight_variable([7*7*64,1024],name='W_fc1')#上一层有7*7*64个神经元,全连接层有1024个神经元 这个数是自己随机定义的
with tf.name_scope('b_fc1'):
b_fc1=bias_variable([1024],name='b_fc1')#1024个节点
with tf.name_scope('h_pool2_flat'):
#把池化层2的输出扁平化为1维 批次的100所以现在的形状是100*7*7*64,转化成1维
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64],name='h_pool2_flat')
with tf.name_scope('wx_plus_b1'):
#求第一个全连接层的输出⭐
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
#用keep_prob来表示神经元的输出概率 就是之前用到的dropout
with tf.name_scope('keep_prob'):
keep_prob=tf.placeholder(tf.float32,name='keep_prob')
with tf.name_scope('h_fc1_drop'):
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob,name='h_fc1_drop')
with tf.name_scope('fc2'):
with tf.name_scope('W_fc2'):
#初始化第二个全连接层
W_fc2=weight_variable([1024,10],name='W_fc2')#10个输出
with tf.name_scope('b_fc2'):
b_fc2=bias_variable([10],name='b_fc2')
with tf.name_scope('softmax'):
#计算输出
prediction=tf.matmul(h_fc1_drop,W_fc2)+b_fc2
#pre_y
pre_y=tf.arg_max(prediction,1)
#后面就都一样了,
with tf.name_scope('cross_entropy'):
#交叉熵代价函数
cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction),name='cross_entropy')
tf.summary.scalar('cross_entropy',cross_entropy)
with tf.name_scope('train'):
#使用AdamOptimizer进行优化
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
#结果存放在一个布尔列表中
correct_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
with tf.name_scope('accuracy'):
#求准确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
tf.summary.scalar('accuracy',accuracy)
#合并所有的summary
merged=tf.summary.merge_all()
上面就是进行了两次卷积—池化的操作,然后进行了两次全连接操作。
然后我们开始对引入的数据进行一些操作,然后输入到我们上面定义的这个网络里。
with tf.Session() as sess:
def dense_to_one_hot(labels_dense, num_classes):
# 获取个数
num_labels = labels_dense.shape[0]
# [0,1*类别数,2*类别数,……]
index_offset = np.arange(num_labels) * num_classes
# 空白操作板 zeros[样本数,类别数]
labels_one_hot = np.zeros((num_labels, num_classes))
# 语言不好解释,看网址:https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
total_y = file['label'].values
file.drop('label', axis=1, inplace=True)
total_x = file.values
total_y = dense_to_one_hot(total_y, 10)
total_x = np.multiply(total_x, 1.0 / 255)
#先将total_x转化为图像格式
total_x_image=sess.run(x_image,feed_dict={x:total_x})
total_x, test_x, total_y, test_y = train_test_split(total_x_image, total_y, test_size=0.1)
#total_x和用于测试的test_x都是四维的了。
# 计算一共多少个批次
batch_size_test = math.floor(total_x.shape[0] / batch_size)
# 使用数据增强算法
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range=0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=False, # randomly flip images
vertical_flip=False) # randomly flip images
# 获取一个batch
def next_batch(dataX,dataY):
xx=datagen.flow(dataX, dataY, batch_size=batch_size,shuffle=True, seed=None, save_to_dir=None, save_prefix='',
save_format='png')[0]
return xx[0],xx[1]
# for batch_num in range(batch_size_test):
# start_index = batch_num * batch_size
# end_index = min((batch_num + 1) * batch_size, len(total_x))
# yield data[start_index:end_index]
total_x=np.array(total_x)
total_y=np.array(total_y)
test_x = np.array(test_x)
test_y = np.array(test_y)
train_writer=tf.summary.FileWriter('../logs/train',sess.graph)
test_writer=tf.summary.FileWriter('../logs/test',sess.graph)
for epoch in range(50):
# batched = next_batch(list(zip(total_x_image, total_y)))
for i in range(batch_size_test): # 批次
#batch_xs, batch_ys = zip(*batch)
# batch_xs = np.array(batch_xs)
#batch_ys = np.array(batch_ys)
batch_xs,batch_ys=next_batch(total_x[i*batch_size:(i+1)*batch_size],total_y[i*batch_size:(i+1)*batch_size])
# 对于y标签进行独热编码处理
# batch_ys = dense_to_one_hot(batch_ys, 10)
sess.run(train_step,feed_dict={x_image:batch_xs,y:batch_ys,keep_prob:0.7})
#记录训练集计算的参数
summary=sess.run(merged,feed_dict={x_image:batch_xs,y:batch_ys,keep_prob:1.0})
train_writer.add_summary(summary,epoch)
acc = sess.run(accuracy, feed_dict={x_image: test_x, y: test_y, keep_prob: 1.0})
print("Iter "+str(epoch)+", Testing Accuracy="+str(acc))
saver.save(sess,r'../model/final_model')
file = pd.read_csv("../data/test.csv")
#28000条数据,4000一次
results=[]
for i in range(7):
total_x = file.values[i*4000:(i+1)*4000]
pred = sess.run(pre_y, feed_dict={x: total_x, keep_prob: 1.0})
results+=pred.ravel().tolist()
data = {
"ImageId": [i for i in range(1, 28001)],
"Label": results
}
pd.DataFrame(data).to_csv(r"E:\TensorFlow\大数据之路\kaggle\Digit_Recongnizer\result\res1.csv",
index=False)
把上面的代码按照顺序复制就可以得到 完整代码,这里不贴出来了。
其实还可以提高准确率,就是使用MNIST数据集,这样样本就多了两倍!让我们看一下全部代码吧:(其实就是相比上面代码加了几行引入MNIST数据)
import tensorflow as tf
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import math
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator,array_to_img,img_to_array,load_img
from tensorflow.examples.tutorials.mnist import input_data
#引入数据
file=pd.read_csv('../data/train.csv')
#每个批次的大小
batch_size=50
#初始化权值
def weight_variable(shape,name):
initial=tf.truncated_normal(shape,stddev=0.1)#生成一个截断正态分布
return tf.Variable(initial,name=name)
#初始化偏置
def bias_variable(shape,name):
initial=tf.constant(0.1,shape=shape)
return tf.Variable(initial,name=name)
#卷积层
def conv2d(x,W):
#2d是二维的意思
#x是一个tensor,形状是[batch,in_height,in_width,in_channels]NHWC关系,分别是批次大小(本例batch_size=100),图片高度,图片宽度,通道数(黑白照片是1,彩色是3)
#w是一个滤波器,tensor,形状是[filter_height,filter_width,in_channels,out_channels],滤波器长,宽,输入和输出通道数
#步长参数,strides[0]=strides[3]=1,strides[1]代表x方向的步长,strides[2]代表y方向的步长
#padding:一个字符串,要么是'SAME'要么是'VALID',对应两种卷积方法,前者补零,后者不会超出平面外部
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#池化层
def max_pool_2x2(x):#这里定义的最大池化的方式,他会取2*2窗口里最大的值
#ksize[1,x,y,1]
#ksize是窗口大小,索引0,3对应的值必须是1,因为是2*2,所以索引1,2对应的值为2,步长对应也是2
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#命名空间
with tf.name_scope('input'):
#定义两个占位符
x=tf.placeholder(tf.float32,[None,784],name='x-input')#28*28
y=tf.placeholder(tf.float32,[None,10],name='y-input')
with tf.name_scope('x_image'):
# 改变x的格式,转为4d的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x, [-1, 28, 28, 1],name='x_image') # -1是指个数不确定 1是通道数
with tf.name_scope('Conv1'):
#初始化第一个卷积层的权值和偏置
# 多少个卷积核返回多少个矩阵
with tf.name_scope('W_conv1'):
W_conv1=weight_variable([5,5,1,32],name='W_conv1')#5*5的采样窗口,32个卷积核从1个平面抽取特征 1的意思是通道数,如果是彩色则为3
with tf.name_scope('b_conv1'):
b_conv1=bias_variable([32],name='b_conv1')#每一个卷积核一个偏置值
#把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
with tf.name_scope('conv2d_1'):
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#[?,28,28,32]
with tf.name_scope('h_pool1'):
h_pool1=max_pool_2x2(h_conv1)#进行max—pooling #[?,14,14,32]
with tf.name_scope('Conv2'):
#初始化第二个卷积层的权值和偏置
with tf.name_scope('W_conv2'):
W_conv2=weight_variable([5,5,32,64],name='W_conv2')#5*5的采样窗口,64个卷积核从32个平面抽取特征 因为前面32个卷积核生成了32个平面图。
with tf.name_scope('b_conv2'):
b_conv2=bias_variable([64],name='b_conv2')#每一个卷积核一个偏置值
#把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
with tf.name_scope('conv2d_2'):
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
with tf.name_scope('h_pool2'):
h_pool2=max_pool_2x2(h_conv2)#进行max—pooling
#多少个卷积核返回多少个矩阵(feature map)哈哈
#因为我们用的是SAME,不是VALID,所以会自动填充,所以卷积之后不是24*24而依然是28*28,这样池化后才是14*14
#28*28的图片第一次卷积后还是28*28,第一次池化后变为14*14
#第二次卷积后,还是14*14,第二次池化后,7*7
#通过上面操作后得到64张7*7的平面
with tf.name_scope('fc1'):
with tf.name_scope('W_fc1'):
#初始化第一个全连接层的权值和偏置值
W_fc1=weight_variable([7*7*64,1024],name='W_fc1')#上一层有7*7*64个神经元,全连接层有1024个神经元 这个数是自己随机定义的
with tf.name_scope('b_fc1'):
b_fc1=bias_variable([1024],name='b_fc1')#1024个节点
with tf.name_scope('h_pool2_flat'):
#把池化层2的输出扁平化为1维 批次的100所以现在的形状是100*7*7*64,转化成1维
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64],name='h_pool2_flat')
with tf.name_scope('wx_plus_b1'):
#求第一个全连接层的输出⭐
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
#用keep_prob来表示神经元的输出概率 就是之前用到的dropout
with tf.name_scope('keep_prob'):
keep_prob=tf.placeholder(tf.float32,name='keep_prob')
with tf.name_scope('h_fc1_drop'):
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob,name='h_fc1_drop')
with tf.name_scope('fc2'):
with tf.name_scope('W_fc2'):
#初始化第二个全连接层
W_fc2=weight_variable([1024,10],name='W_fc2')#10个输出
with tf.name_scope('b_fc2'):
b_fc2=bias_variable([10],name='b_fc2')
with tf.name_scope('softmax'):
#计算输出
prediction=tf.matmul(h_fc1_drop,W_fc2)+b_fc2
#pre_y
pre_y=tf.arg_max(prediction,1)
#后面就都一样了,
with tf.name_scope('cross_entropy'):
#交叉熵代价函数
cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction),name='cross_entropy')
tf.summary.scalar('cross_entropy',cross_entropy)
with tf.name_scope('train'):
#使用AdamOptimizer进行优化
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
#结果存放在一个布尔列表中
correct_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
with tf.name_scope('accuracy'):
#求准确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
tf.summary.scalar('accuracy',accuracy)
#合并所有的summary
merged=tf.summary.merge_all()
with tf.Session() as sess:
def dense_to_one_hot(labels_dense, num_classes):
# 获取个数
num_labels = labels_dense.shape[0]
# [0,1*类别数,2*类别数,……]
index_offset = np.arange(num_labels) * num_classes
# 空白操作板 zeros[样本数,类别数]
labels_one_hot = np.zeros((num_labels, num_classes))
# 语言不好解释,看网址:https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
total_y = file['label'].values
file.drop('label', axis=1, inplace=True)
total_x = file.values
total_y = dense_to_one_hot(total_y, 10)
# print(total_x.shape)
# print(total_y.shape)
mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # 独热编码
total_x1=mnist.train.images
total_y1 = mnist.train.labels
# print(total_x1.shape)
# print(total_y1.shape)
#合并MNIST_data和题中所给数据集
total_x=np.concatenate((total_x,total_x1),axis=0)
total_y=np.concatenate((total_y,total_y1),axis=0)
# print(total_x.shape)
# print(total_y.shape)
total_x = np.multiply(total_x, 1.0 / 255)
#先将total_x转化为图像格式
total_x_image=sess.run(x_image,feed_dict={x:total_x})
total_x, test_x, total_y, test_y = train_test_split(total_x_image, total_y, test_size=0.1)
#total_x和用于测试的test_x都是四维的了。
# 计算一共多少个批次
batch_size_test = math.floor(total_x.shape[0] / batch_size)
# print(batch_size_test)
# 对训练数据total_x,total_y增强数据
# 使用数据增强算法
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range=0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=False, # randomly flip images
vertical_flip=False) # randomly flip images
# 获取一个batch
def next_batch(dataX,dataY):
xx=datagen.flow(dataX, dataY, batch_size=batch_size,shuffle=True, seed=None, save_to_dir=None, save_prefix='',
save_format='png')[0]
return xx[0],xx[1]
# for batch_num in range(batch_size_test):
# start_index = batch_num * batch_size
# end_index = min((batch_num + 1) * batch_size, len(total_x))
# yield data[start_index:end_index]
total_x=np.array(total_x)
total_y=np.array(total_y)
test_x = np.array(test_x)
test_y = np.array(test_y)
train_writer=tf.summary.FileWriter('../logs/train',sess.graph)
test_writer=tf.summary.FileWriter('../logs/test',sess.graph)
# print(total_x.shape)
# print(total_y.shape)
# print(total_x[0*128:(0+1)*128].shape)
for epoch in range(50):
# batched = next_batch(list(zip(total_x_image, total_y)))
for i in range(batch_size_test): # 批次
#batch_xs, batch_ys = zip(*batch)
# batch_xs = np.array(batch_xs)
#batch_ys = np.array(batch_ys)
batch_xs,batch_ys=next_batch(total_x[i*batch_size:(i+1)*batch_size],total_y[i*batch_size:(i+1)*batch_size])
# 对于y标签进行独热编码处理
# batch_ys = dense_to_one_hot(batch_ys, 10)
sess.run(train_step,feed_dict={x_image:batch_xs,y:batch_ys,keep_prob:0.7})
#记录训练集计算的参数
summary=sess.run(merged,feed_dict={x_image:batch_xs,y:batch_ys,keep_prob:1.0})
train_writer.add_summary(summary,epoch)
acc = sess.run(accuracy, feed_dict={x_image: test_x, y: test_y, keep_prob: 1.0})
print("Iter "+str(epoch)+", Testing Accuracy="+str(acc))
saver.save(sess,r'../model/final_model')
file = pd.read_csv("../data/test.csv")
#28000条数据,4000一次
results=[]
for i in range(7):
total_x = file.values[i*4000:(i+1)*4000]
pred = sess.run(pre_y, feed_dict={x: total_x, keep_prob: 1.0})
results+=pred.ravel().tolist()
data = {
"ImageId": [i for i in range(1, 28001)],
"Label": results
}
pd.DataFrame(data).to_csv(r"E:\TensorFlow\大数据之路\kaggle\Digit_Recongnizer\result\res1.csv",
index=False)