python 神经网络调教程序

本文介绍了一个使用PyNeurGen库训练神经网络来预测正弦波的例子。通过生成正弦波数据集并利用随机生成的输入进行训练,展示了如何设置网络结构、调整学习率以及评估模型性能。此外,还提供了使用Matplotlib绘制预测结果和误差的图表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=large]
#from http://pyneurgen.sourceforge.net/tutorial_nn.html

import random
import math

from pyneurgen.neuralnet import NeuralNet
from pyneurgen.nodes import BiasNode, Connection

pop_len = 360
factor = 1.0 / float(pop_len)
population = [
(i, math.sin(float(i) * factor )) for i in range(pop_len)
]

all_inputs = []
all_targets = []

def population_gen(population):
pop_sort = [item for item in population]
random.shuffle(pop_sort)
for item in pop_sort:
yield item

# Build the inputs
for position, target in population_gen(population):
pos = float(position)
all_inputs.append([random.random(), pos * factor])
all_targets.append([target])

net = NeuralNet()
net.init_layers(2, [10], 1)
net.randomize_network()
net.learnrate = .20

net.randomize_network()
net.set_all_inputs(all_inputs)
net.set_all_targets(all_targets)
length = len(all_inputs)

learn_end_point = int(length * .8)
net.set_learn_range(0, learn_end_point)
net.set_test_range(learn_end_point + 1, length - 1)
net.layers[1].set_activation_type('tanh')
net.learn(epochs=125, show_epoch_results=True,random_testing=False)
mse = net.test()

import matplotlib
from pylab import plot, legend, subplot, grid
from pylab import xlabel, ylabel, show, title

test_positions = [item[0][1] * 1000.0 for item in net.get_test_data()]

all_targets1 = [item[0][0] for item in net.test_actuals_targets]
allactuals = [item[1][0] for item in net.test_actuals_targets]

# This is quick and dirty, but it will show the results
subplot(3, 1, 1)
plot([i[1] for i in population])
title("Population")
grid(True)

subplot(3, 1, 2)
plot(test_positions, all_targets1, 'bo', label='targets')
plot(test_positions, allactuals, 'ro', label='actuals')
grid(True)
legend(loc='lower left', numpoints=1)
title("Test Target Points vs Actual Points")

subplot(3, 1, 3)
plot(range(1, len(net.accum_mse) + 1, 1), net.accum_mse)
xlabel('epochs')
ylabel('mean squared error')
grid(True)
title("Mean Squared Error by Epoch")

show()

[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值