神经网络算法(Nerual Networks)应用

1. 关于非线性转化方程(non-linear transformation function)

sigmoid函数(S 曲线)用来作为activation function:
1.1 双曲函数(tanh)
1.2 逻辑函数(logistic function)

2. 实现一个简单的神经网络算法

# -*- coding:utf-8 -*-
import numpy as np


def tanh(x):
    return np.tanh(x)#双曲函数

def tanh_deriv(x):
    return 1.0 - np.tanh(x)*np.tanh(x)#双曲函数的一阶导数

def logistic(x):
    return 1/(1 + np.exp(-x))#逻辑函数

def logistic_derivative(x):
    return logistic(x)*(1-logistic(x))#逻辑函数的一阶导数


class NeuralNetwork:
    def __init__(self, layers, activation='tanh'):
        """
        :param layers: A list containing the number of units in each layer.
        Should be at least two values#[10,2,2]
        列表中圆锁的个数对应着一共有几层,数字的值对应着几个神经元,一共三层,
        神经元个数分别为 10 2 2
        :param activation: The activation function to be used. Can be
        "logistic" or "tanh"
        """
        if activation == 'logistic':
            self.activation = logistic
            self.activation_deriv = logistic_derivative
        elif activation == 'tanh':
            self.activation = tanh
            self.activation_deriv = tanh_deriv

        self.weights = []
        for i in range(1, len(layers) - 1):
            self.weights.append((2*np.random.random((layers[i - 1] + 1, layers[i] + 1))-1)*0.25)
            self.weights.append((2*np.random.random((layers[i] + 1, layers[i + 1]))-1)*0.25)

    def fit(self, X, y, learning_rate=0.2, epochs=10000):#每次抽取一部分数据训练模型,一次训练就是 1epoch
        X = np.atleast_2d(X)
        temp = np.ones([X.shape[0], X.shape[1]+1])
        temp[:, 0:-1] = X  # adding the bias unit to the input layer
        X = temp
        y = np.array(y)

        for k in range(epochs):#随机选一个X的实例,对随机网络进行更新
            i = np.random.randint(X.shape[0])
            a = [X[i]]

            for l in range(len(self.weights)):  #going forward network, for each layer
                a.append(self.activation(np.dot(a[l], self.weights[l])))# dot()这是个内积  #Computer the node value for each layer (O_i) using activation function
            error = y[i] - a[-1]  #Computer the error at the top layer
            deltas = [error * self.activation_deriv(a[-1])] #For output layer, Err calculation (delta is updated error)

            #Staring backprobagation
            for l in range(len(a) - 2, 0, -1): # we need to begin at the second to last layer
                #Compute the updated error (i,e, deltas) for each node going from top layer to input layer

                deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))
            deltas.reverse()
            for i in range(len(self.weights)):
                layer = np.atleast_2d(a[i])
                delta = np.atleast_2d(deltas[i])
                self.weights[i] += learning_rate * layer.T.dot(delta)

    def predict(self, x):
        x = np.array(x)
        temp = np.ones(x.shape[0]+1)
        temp[0:-1] = x
        a = temp
        for l in range(0, len(self.weights)):
            a = self.activation(np.dot(a, self.weights[l]))
        return a

第二个例子

#!/usr/bin/python
# -*- coding:utf-8 -*-

# 每个图片8x8  识别数字:0,1,2,3,4,5,6,7,8,9

import numpy as np
from sklearn.datasets import load_digits #下载数据的库
from sklearn.metrics import confusion_matrix, classification_report
#这是一个对结果衡量的包,里面有现成的函数
from sklearn.preprocessing import LabelBinarizer 
# 对于标称型数据来说,preprocessing.LabelBinarizer是一个很好用的工具。
# 比如可以把yes和no转化为0和1,或是把incident和normal转化为0和1。
# 当然,对于两类以上的标签也是适用的。
from NNdemo1 import NeuralNetwork #我这里的NNdemo1是因为我上一个程序起的名字是NNdemo1.py
from sklearn.model_selection import train_test_split #交叉验证


digits = load_digits()#装载数据集
X = digits.data#特征量
y = digits.target#标签
X -= X.min()  # normalize the values to bring them into the range 0-1
X /= X.max()   #进行一个简单的预处理,归一化

nn = NeuralNetwork([64, 100, 10], 'logistic')
#层数可以自己定,8*8 = 64个像素点,64个维度,输出层因为要分出0-9所以是9个,隐藏层自己可以灵活点
X_train, X_test, y_train, y_test = train_test_split(X, y)#分测试集和训练集
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)
print "start fitting"
nn.fit(X_train, labels_train, epochs=3000)
predictions = []
for i in range(X_test.shape[0]):
    o = nn.predict(X_test[i])
    predictions.append(np.argmax(o)) #通过argmax可以看到第几个数对应最大概率
print confusion_matrix(y_test, predictions)
#y_test测试集真实的标记,prediction我们预测出来的标记,通过这个绘图工具我们就能看出有多少是预测正确的
print classification_report(y_test, predictions)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值