稀疏自编码器tensorflow

本文介绍了一种无监督机器学习算法——稀疏自编码器的实现过程,该算法能够提取输入特征并进行数据压缩。文中详细展示了使用TensorFlow实现的具体步骤,包括参数初始化、代价函数计算及可视化等。

        自编码器是一种无监督机器学习算法,通过计算自编码的输出与原输入的误差,不断调节自编码器的参数,最终训练出模型。自编码器可以用于压缩输入信息,提取有用的输入特征。如,[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]四比特信息可以压缩成两位,[0,0],[1,0],[1,1],[0,1]。此时,自编码器的中间层的神经元个数为2。但是,有时中间隐藏层的神经元个数可能超过输出,此时需要通过稀疏因子调节代价函数,让中间隐藏层的神经元信息大部分接近于0但不为0.自编码器具体推导详见http://ufldl.stanford.edu/wiki/index.php/%E8%87%AA%E7%BC%96%E7%A0%81%E7%AE%97%E6%B3%95%E4%B8%8E%E7%A8%80%E7%96%8F%E6%80%A7。

以下是通过tensorflow实现的稀疏自编码器。

1、初始化参数

input_nodes = 8*8 //输入节点数
hidden_size = 100//隐藏节点数
output_nodes = 8*8//输出节点数

2、初始化训练集数据,从mat文件中读取图像块,随机生成10000个8*8的图像块

def sampleImage():
    mat = scipy.io.loadmat('F:/ml/code/IMAGES.mat')
    pic = mat['IMAGES']
    shape = pic.shape
    patchsize = 8
    numpatches = 1000
    patches = []
    i = np.random.randint(0, shape[0]-patchsize,numpatches)
    j = np.random.randint(0, shape[1]-patchsize, numpatches)
    k = np.random.randint(0, shape[2], numpatches)


    for l in range(numpatches):
        temp = pic[i[l]:(i[l]+patchsize), j[l]:(j[l]+patchsize), k[l]]
        temp = temp.reshape(patchsize*patchsize)
        patches.append(temp)
    return patches

3、通过xvaier初始化第一层的权重值,xvaier初始化详见http://blog.youkuaiyun.com/shuzfan/article/details/51338178

def xvaier_init(input_size, output_size):
    low = -np.sqrt(6.0/(input_nodes+output_nodes))
    high = -low
    return tf.random_uniform((input_size, output_size), low, high, dtype = tf.float32)

4、计算代价函数,代价函数由三部分组成,均方差项,权重衰减项,以及稀疏因子项

def computecost(w,b,x,w1,b1):
    p = 0.1
    beta = 3
    lamda = 0.00001
    
    hidden_output = tf.sigmoid(tf.matmul(x,w) + b)
    pj = tf.reduce_mean(hidden_output, 0)
    sparse_cost = tf.reduce_sum(p*tf.log(p/pj)+(1-p)*tf.log((1-p)/(1-pj)))
    output = tf.sigmoid(tf.matmul(hidden_output,w1)+b1)
    regular = lamda*(tf.reduce_sum(w*w)+tf.reduce_sum(w1*w1))/2
    cross_entropy = tf.reduce_mean(tf.pow(output - x, 2))/2 +sparse_cost*beta + regular #+ regular+sparse_cost*beta 
    return cross_entropy, hidden_output, output

5、可视化自编码器:为了使隐藏单元得到最大激励(隐藏单元需要什么样的特征输入),将这些特征输入显示出来。

def show_image(w):
    sum = np.sqrt(np.sum(w**2, 0))
    changedw = w/sum
    a,b = changedw.shape
    c = np.sqrt(a*b)
    d = int(np.sqrt(a))
    e = int(c/d)
    buf = 1
    newimage = -np.ones((buf+(d+buf)*e,buf+(d+buf)*e))
    k = 0
    for i in range(e):
        for j in range(e):
            maxvalue = np.amax(changedw[:,k])
            if(maxvalue<0):
                maxvalue = -maxvalue
            newimage[(buf+i*(d+buf)):(buf+i*(d+buf)+d),(buf+j*(d+buf)):(buf+j*(d+buf)+d)] = np.reshape(changedw[:,k],(d,d))/maxvalue
            k+=1
    
    plt.figure("beauty")
    plt.imshow(newimage)
    plt.axis('off')
    plt.show()   

6、主函数,通过AdamOptimizer下降误差,调节参数

def main():
    w = tf.Variable(xvaier_init(input_nodes, hidden_size))
    b = tf.Variable(tf.truncated_normal([hidden_size],0.1))   
    x = tf.placeholder(tf.float32, shape = [None, input_nodes])
    w1 = tf.Variable(tf.truncated_normal([hidden_size,input_nodes], -0.1, 0.1))
    b1 = tf.Variable(tf.truncated_normal([output_nodes],0.1))


    cost, hidden_output, output = computecost(w,b,x,w1,b1)
    train_step = tf.train.AdamOptimizer().minimize(cost)
    train_x = sampleImage()
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    
    for i in range(100000):
        _,hidden_output_, output_,cost_,w_= sess.run([train_step, hidden_output, output,cost,w], feed_dict = {x : train_x})
        if i%1000 == 0:
            print(hidden_output_)
            print(output_)
            print(cost_)
    np.save("weights1.npy", w_)
    show_image(w_)

        本次实验过程中,除了整体思想,最难的还是调节参数。使用稀疏因子加入代价函数,个人觉得隐藏层的神经元数要多于输入层,结果才比较理想。希望大家多多指教。

代码地址:https://github.com/summersunshine1/datamining/tree/master/sparseencoder


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值