theano学习搭建自己的神经网络之类层

本文详细介绍了如何使用Theano库定义神经网络层类,并通过实例演示了其在逻辑回归中的应用。从创建类、初始化参数、定义激活函数,到构建逻辑回归模型并进行训练,全程代码解析清晰,帮助读者深入理解神经网络的工作原理。

定义一个类层,然后套用

from __future__ import print_function
import theano
import theano.tensor as T
import numpy as np

#-----------------------------定义神经网络层类,然后可以套用------------------------------#
class Layer(object):
    def __init__(self, inputs, in_size, out_size, activation_function=None):#类的构造函数
        self.W = theano.shared(np.random.normal(0, 1, (in_size, out_size)))#权重为实时变的值,所以设定为shared类型,这里设初始值为0到1之间的值,矩阵规格为insize-outsize
        self.b = theano.shared(np.zeros((out_size, )) + 0.1)#权重为实时变的值,所以设定为shared类型,偏置是一个向量,规格为outsize-1
        self.Wx_plus_b = T.dot(inputs, self.W) + self.b
        self.activation_function = activation_function
        if activation_function is None:
            self.outputs = self.Wx_plus_b
        else:
            self.outputs = self.activation_function(self.Wx_plus_b)

"""
to define the layer like this:
l1 = Layer(inputs, 1, 10, T.nnet.relu)
l2 = Layer(l1.outputs, 10, 1, None)
"""

逻辑回归:
 

import theano
import theano.tensor as T
import numpy as np
import matplotlib.pyplot as plt

#---------------------------------定义类层-----------------------------------#
class Layer(object):
    def __init__(self, inputs, in_size, out_size, activation_function=None):
        self.W = theano.shared(np.random.normal(0, 1, (in_size, out_size)))
        self.b = theano.shared(np.zeros((out_size,)) + 0.1)#注:不能是np.zeros((out_size,1))+1),因为偏置不用来乘的,是加到权重乘以输入之后的值
        self.Wx_plus_b = T.dot(inputs, self.W) + self.b
        self.activation_function = activation_function
        if activation_function is None:
            self.outputs = self.Wx_plus_b
        else:
            self.outputs = self.activation_function(self.Wx_plus_b)

#---------------------------------伪造数据-------------------------------------#
# Make up some fake data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]#[:,np.newaxis]做成矩阵
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise        # y = x^2 - 0.5 + wihtenoise
print(np.linspace(-1,1,300))
print(x_data)
print(np.linspace(-1,1,300).shape)
print(x_data.shape)

#-----------------------------------画出数据--------------------------------------#
# show the fake data
plt.scatter(x_data, y_data)
plt.show()

#------------------------------------搭建网络---------------------------------------#
x = T.dmatrix('x')
y = T.dmatrix('y')
#定义层
l1 = Layer(x,1,10,T.nnet.relu)
l2 = Layer(l1.outputs,10,1,None)
#计算代价
cost = T.mean(T.square(l2.outputs - y))
#计算梯度
gW1,gb1,gW2,gb2 = T.grad(cost,[l1.W,l1.b,l2.W,l2.b])
#训练过程
learning_rate = 0.05
train = theano.function(
    inputs=[x, y],
    updates=[(l1.W, l1.W - learning_rate * gW1),
             (l1.b, l1.b - learning_rate * gb1),
             (l2.W, l2.W - learning_rate * gW2),
             (l2.b, l2.b - learning_rate * gb2)],
    outputs=cost)
#预测值
#predict = theano.function(inputs=[x],outputs=l2.outputs)
#训练
for i in range(1000):
    err = train(x_data,y_data)
    if i%50 == 0:
        print(err)

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值