李宏毅-机器学习HW3

利用CNN解决7分类的问题,模型直接套用的是之前实验的简单模型,2convs,2maxpoolings,2Fc,softamx

import tensorflow as tf
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import cv2
# 修改为train.csv在本地的相对或绝对地址
path = 'D:\\train.csv'
# 读取数据
df = pd.read_csv(path)
# 提取label数据
df_y = df[['label']]
# 提取feature(即像素)数据
df_x = df[['feature']]
df_x = df[['feature']]
# 将label写入label.csv
df_y.to_csv('label.csv', index=False, header=False)
# 将feature数据写入data.csv
df_x.to_csv('data.csv', index=False, header=False)
data = np.loadtxt('data.csv')
label=np.loadtxt('label.csv')
class_n=int(np.max(label))+1

label=np.array(label,dtype=int)
Label=np.zeros((len(label),class_n))
for i in range(len(label)):
    Label[i,label[i]]=1

X_train,X_test,y_train,y_test=train_test_split(data,Label,train_size=0.8)

count_zhonglei=class_n
def weight_variable(shape):
    # 产生随机变量
    # truncated_normal:选取位于正态分布均值=0.1附近的随机值
    initial = tf.truncated_normal(shape, stddev=0.01)
    return tf.Variable(initial)
 
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
 
def conv2d(x, W):
    # stride = [1,水平移动步长,竖直移动步长,1]
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')
 
def max_pool_2x2(x):
    # stride = [1,水平移动步长,竖直移动步长,1]
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
 
x = tf.placeholder(tf.float32, shape=[None,48*48],name='x')
y_ = tf.placeholder(tf.float32, shape=[None, count_zhonglei],name='y_')
keep_prob = tf.placeholder(tf.float32,name='k_p')
x_image = tf.reshape(x, [-1,48,48,1])
#print(x_image.shape)  #[n_samples,28,28,1]
 
#卷积层1网络结构定义
#卷积核1:patch=5×5;in size 1;out size 32;激活函数reLU非线性处理
with tf.variable_scope("conv1"):

    W_conv1 = weight_variable([3, 3, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)         #output size 28*28*32
    h_pool1 = max_pool_2x2(h_conv1)                                  #output size 14*14*32#卷积层2网络结构定义
 
#卷积核2:patch=5×5;in size 32;out size 64;激活函数reLU非线性处理
with tf.variable_scope("conv2"):

    W_conv2 = weight_variable([3, 3, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)         #output size 14*14*64
    h_pool2 = max_pool_2x2(h_conv2)                                  #output size 7 *7 *64
 
# 全连接层1
with tf.variable_scope("fc1"):

    W_fc1 = weight_variable([11*11*64,1024])
    b_fc1 = bias_variable([1024])
    h_pool2_flat = tf.reshape(h_pool2, [-1,11*11*64])   #[n_samples,7,7,64]->>[n_samples,7*7*64]
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # 减少 计算量dropout

# 全连接层1
W_fc2 = weight_variable([1024,1024])
b_fc2 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1,1024])   #[n_samples,7,7,64]->>[n_samples,7*7*64]
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
h_fc2_drop = tf.nn.dropout(h_fc2, keep_prob) # 减少计算量dropout




# 全连接层2
with tf.variable_scope("fc2"):

    W_fc3 = weight_variable([1024, class_n])
    b_fc3 = bias_variable([class_n])
    prediction = tf.matmul(h_fc1_drop, W_fc3) + b_fc3
# prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

def next_batch(train_data, train_target, batch_size):  
    index = [ i for i in range(0,len(train_target)) ]  
    np.random.shuffle(index)  
    batch_data = [] 
    batch_target = []  
    for i in range(0,batch_size):  
        batch_data.append(train_data[index[i]])  
        batch_target.append(train_target[index[i]])  
    return batch_data, batch_target 

#二次代价函数:预测值与真实值的误差
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=prediction))
 
#梯度下降法:数据太庞大,选用AdamOptimizer优化器
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
 
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))
#求准确率
#accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#saver = tf.train.Saver()  # defaults to saving all variables
tf.add_to_collection("predict", prediction)

max_acc=0
#max_acc=0.99538463354110718
#10000次
fig_loss = np.zeros([20000],dtype="float")
fig_accuracy = np.zeros([20000],dtype="float")
#tf.reset_default_graph() 
sess=tf.Session()
sess.run(tf.global_variables_initializer())
def batch_data(X,y,batch):
    all_len=len(y)
    l=list(range(all_len))
    random.shuffle(l)
    ll=l[:batch]
    return X[ll],y[ll]

for i in range(20000):
    batch1 = next_batch(X_train,y_train,128)
                
    if i % 200 == 0:
        fig_loss[i]= sess.run(loss,feed_dict={x: batch1[0], y_: batch1[1],keep_prob: 1.0})
        fig_accuracy[i] = sess.run(accuracy,feed_dict={x: X_test, y_: y_test,keep_prob: 1.0})
        
        print("step", i, "test accuracy", fig_accuracy[i])
        print("step", i, "train loss", fig_loss[i])
                    
    train_step.run(session=sess,feed_dict={x: batch1[0], y_: batch1[1],keep_prob: 0.5})

 

你可能感兴趣的:(机器学习)