神经网络示例源代码(最好是Python)

12 投票
3 回答
15094 浏览
提问于 2025-04-15 14:46

我想知道有没有人能分享一些用Python写的神经网络的示例代码。如果有人知道什么教程,能一步一步教的那就太好了,不过单纯的示例代码也很不错!

谢谢!

3 个回答

2

这里有一个关于概率神经网络的教程:http://www.youtube.com/watch?v=uAKu4g7lBxU

还有我用Python写的实现代码:

import math

data = {'o' : [(0.2, 0.5), (0.5, 0.7)],
        'x' : [(0.8, 0.8), (0.4, 0.5)],
        'i' : [(0.8, 0.5), (0.6, 0.3), (0.3, 0.2)]}

class Prob_Neural_Network(object):
    def __init__(self, data):
        self.data = data

    def predict(self, new_point, sigma):
        res_dict = {}
        np = new_point
        for k, v in self.data.iteritems():
            res_dict[k] = sum(self.gaussian_func(np[0], np[1], p[0], p[1], sigma) for p in v)
        return max(res_dict.iteritems(), key=lambda k : k[1])

    def gaussian_func(self, x, y, x_0, y_0, sigma):
        return  math.e ** (-1 *((x - x_0) ** 2 + (y - y_0) ** 2) / ((2 * (sigma ** 2))))

prob_nn = Prob_Neural_Network(data)
res = prob_nn.predict((0.2, 0.6), 0.1)

结果:

>>> res
('o', 0.6132686067117191)
2

你可能想看看 Monte

Monte(python)是一个用Python写的框架,主要用于构建基于梯度学习的机器,比如神经网络、条件随机场、逻辑回归等等。Monte里面有一些模块(这些模块包含参数、成本函数和梯度函数)和训练器(可以通过最小化成本函数来调整模块的参数,以适应训练数据)。

这些模块通常是由其他模块组成的,而这些模块又可以包含其他模块,依此类推。像这样的可分解系统的梯度可以通过反向传播来计算。

4

在Ubuntu论坛上发现了一个有趣的讨论,大家可以去看看这个链接:http://ubuntuforums.org/showthread.php?t=320257

import time
import random

# Learning rate:
# Lower  = slower
# Higher = less precise
rate=.2

# Create random weights
inWeight=[random.uniform(0, 1), random.uniform(0, 1)]

# Start neuron with no stimuli
inNeuron=[0.0, 0.0]

# Learning table (or gate)
test =[[0.0, 0.0, 0.0]]
test+=[[0.0, 1.0, 1.0]]
test+=[[1.0, 0.0, 1.0]]
test+=[[1.0, 1.0, 1.0]]

# Calculate response from neural input
def outNeuron(midThresh):
    global inNeuron, inWeight
    s=inNeuron[0]*inWeight[0] + inNeuron[1]*inWeight[1]
    if s>midThresh:
        return 1.0
    else:
        return 0.0

# Display results of test
def display(out, real):
        if out == real:
            print str(out)+" should be "+str(real)+" ***"
        else:
            print str(out)+" should be "+str(real)

while 1:
    # Loop through each lesson in the learning table
    for i in range(len(test)):
        # Stimulate neurons with test input
        inNeuron[0]=test[i][0]
        inNeuron[1]=test[i][1]
        # Adjust weight of neuron #1
        # based on feedback, then display
        out = outNeuron(2)
        inWeight[0]+=rate*(test[i][2]-out)
        display(out, test[i][2])
        # Adjust weight of neuron #2
        # based on feedback, then display
        out = outNeuron(2)
        inWeight[1]+=rate*(test[i][2]-out)
        display(out, test[i][2])
        # Delay
        time.sleep(1)

补充一下:还有一个叫做Chainer的框架,大家可以了解一下这个链接:https://pypi.python.org/pypi/chainer/1.0.0

撰写回答