楼主: Lisrelchen
2969 6

[书籍介绍] ffnet:Feed-forward neural network for Python [推广有奖]

  • 0关注
  • 62粉丝

VIP

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
49957 个
通用积分
79.5487
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
  1. ### Digits recognition example for ffnet ###

  2. # Training file (data/ocr.dat) contains 68 patterns - first 58
  3. # are used for training and last 10 are used for testing.
  4. # Each pattern contains 64 inputs which define 8x8 bitmap of
  5. # the digit and last 10 numbers are the targets (10 targets for 10 digits).
  6. # Layered network architecture is used here: (64, 10, 10, 10).

  7. from ffnet import ffnet, mlgraph, readdata

  8. # Generate standard layered network architecture and create network
  9. conec = mlgraph((64,10,10,10))
  10. net = ffnet(conec)

  11. # Read data file
  12. print "READING DATA..."
  13. data = readdata( 'data/ocr.dat', delimiter = ' ' )
  14. input =  data[:, :64] #first 64 columns - bitmap definition
  15. target = data[:, 64:] #the rest - 10 columns for 10 digits

  16. # Train network with scipy tnc optimizer - 58 lines used for training
  17. print "TRAINING NETWORK..."
  18. net.train_tnc(input[:58], target[:58], maxfun = 2000, messages=1)

  19. # Test network - remaining 10 lines used for testing
  20. print
  21. print "TESTING NETWORK..."
  22. output, regression = net.test(input[58:], target[58:], iprint = 2)

  23. ############################################################
  24. # Make a plot of a chosen digit along with the network guess
  25. try:
  26.     from pylab import *
  27.     from random import randint

  28.     digitpat = randint(58, 67) #Choose testing pattern to plot

  29.     subplot(211)
  30.     imshow(input[digitpat].reshape(8,8), interpolation = 'nearest')

  31.     subplot(212)
  32.     N = 10  # number of digits / network outputs
  33.     ind = arange(N)   # the x locations for the groups
  34.     width = 0.35       # the width of the bars
  35.     bar(ind, net(input[digitpat]), width, color='b') #make a plot
  36.     xticks(ind+width/2., ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0'))
  37.     xlim(-width,N-width)
  38.     axhline(linewidth=1, color='black')
  39.     title("Trained network (64-10-10-10) guesses a digit above...")
  40.     xlabel("Digit")
  41.     ylabel("Network outputs")

  42.     show()
  43. except ImportError, e:
  44.     print "Cannot make plots. For plotting install matplotlib.\n%s" % e
复制代码
https://pypi.python.org/pypi/ffnet
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:network forward python Neural ward standard training network testing example

已有 1 人评分论坛币 热心指数 收起 理由
狂热的爱好者 + 20 + 3 精彩帖子

总评分: 论坛币 + 20  热心指数 + 3   查看全部评分

本帖被以下文库推荐

沙发
Lisrelchen 发表于 2014-10-11 05:18:11 |只看作者 |坛友微信交流群
  1. ### Sine training example for ffnet ###

  2. from ffnet import ffnet
  3. from math import pi, sin, cos

  4. # Let's define network connectivity by hand:
  5. conec = [(1, 2), (1, 3), (1, 4), (1, 5), (2, 6), (3, 6), (4, 6), (5, 6), \
  6.          (0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]
  7. # Note 1: Biases in ffnet are handled as the connections
  8. #         from special node numbered 0. Input nodes cannot be biased.
  9. # Note 2: Node numbering and order of links in conec is meaningless,
  10. #         but the connections have to be from source to target.
  11. # Note 3: The same connectivity can be obtained using mlgraph function
  12. #         provided with ffnet (layered architecture (1,4,1)).

  13. # Network creation
  14. net = ffnet(conec)

  15. # Generation of training data (sine values for x from 0 to 2*pi)
  16. patterns = 16
  17. input = [ [ 0. ] ] + [ [ k*2*pi/patterns ] for k in xrange(1, patterns + 1) ]
  18. target = [ [ sin(x[0]) ] for x in input ]

  19. # Training network
  20. #first find good starting point with genetic algorithm (not necessary, but may be helpful)
  21. print "FINDING STARTING WEIGHTS WITH GENETIC ALGORITHM..."
  22. net.train_genetic(input, target, individuals=20, generations=500)
  23. #then train with scipy tnc optimizer
  24. print "TRAINING NETWORK..."
  25. net.train_tnc(input, target, maxfun = 5000, messages=1)

  26. # Testing network
  27. print
  28. print "TESTNG NETWORK..."
  29. output, regression = net.test(input, target, iprint = 2)

  30. #################
  31. # Make some plots
  32. try:
  33.     from pylab import *
  34.     points = 128
  35.     xaxis = [ 0. ] + [ k*2*pi/points for k in xrange(1, points + 1) ]
  36.     sine = [ sin(x) for x in xaxis ]
  37.     cosine = [ cos(x) for x in xaxis ]
  38.     netsine = [ net([x])[0] for x in xaxis]
  39.     netcosine = [ net.derivative([x])[0][0] for x in xaxis ]

  40.     subplot(211)
  41.     plot(xaxis, sine, 'b--', xaxis, netsine, 'k-')
  42.     legend(('sine', 'network output'))
  43.     grid(True)
  44.     title('Outputs of trained network.')

  45.     subplot(212)
  46.     plot(xaxis, cosine, 'b--', xaxis, netcosine, 'k-')
  47.     legend(('cosine', 'network derivative'))
  48.     grid(True)
  49.     show()
  50. except ImportError:
  51.     print "Cannot make plots. For plotting install matplotlib..."
复制代码


使用道具

藤椅
Lisrelchen 发表于 2014-10-11 05:19:14 |只看作者 |坛友微信交流群
  1. ### XOR problem example for ffnet ###

  2. from ffnet import ffnet, mlgraph

  3. # Generate standard layered network architecture and create network
  4. conec = mlgraph((2,2,1))
  5. net = ffnet(conec)

  6. # Define training data
  7. input = [[0.,0.], [0.,1.], [1.,0.], [1.,1.]]
  8. target  = [[1.], [0.], [0.], [1.]]

  9. # Train network
  10. #first find good starting point with genetic algorithm (not necessary, but may be helpful)
  11. print "FINDING STARTING WEIGHTS WITH GENETIC ALGORITHM..."
  12. net.train_genetic(input, target, individuals=20, generations=500)
  13. #then train with scipy tnc optimizer
  14. print "TRAINING NETWORK..."
  15. net.train_tnc(input, target, maxfun = 1000, messages=1)

  16. # Test network
  17. print
  18. print "TESTING NETWORK..."
  19. output, regression = net.test(input, target, iprint = 2)

  20. # Save/load/export network
  21. from ffnet import savenet, loadnet, exportnet
  22. print "Network is saved..."
  23. savenet(net, "xor.net")
  24. print "Network is reloaded..."
  25. net = loadnet("xor.net")
  26. print "Network is tested again, but nothing is printed..."
  27. output, regression = net.test(input, target, iprint = 0)
  28. print
  29. print "Exporting trained network to the fortran source..."
  30. exportnet(net, "xor.f")
  31. print "Done..."
  32. print "Look at the generated xor.f file."
  33. print "Note: you must compile xor.f along with the ffnet.f"
  34. print "file which can be found in ffnet sources."
复制代码


使用道具

板凳
Lisrelchen 发表于 2014-10-11 05:20:00 |只看作者 |坛友微信交流群
  1. ### Stock Problem Example for ffnet ###

  2. # Data and description for this example is borrowed from:
  3. # http://www.scientific-consultants.com/nnbd.html
  4. #
  5. #
  6. # Training data consists of Black-Scholes option prices
  7. # for volatility levels running from 20 percent to 200 percent,
  8. # for time remaining running from 5 to 15 days, and for strike price
  9. # running from 70 dollars to 130 dollars. The stock price was set to
  10. # 100 dollars and the interest rate to 0 percent when generating
  11. # the data.
  12. #
  13. # The data is "difficult" in that (for a neural network to
  14. # practically emulate Black-Scholes) a very tight fit is required.
  15. # The R-squared should be at least 0.999999 or better, and the largest
  16. # absolute error must be less than 0.05 dollars (the price increment
  17. # for most options) or, better yet, less than 0.01 dollars.
  18. #
  19. #
  20. # So let's try.
  21. # Attention: training might be a long process since we train a big network.

  22. from ffnet import ffnet, mlgraph, readdata
  23. from numpy import array

  24. # Generate standard layered network architecture and create network
  25. conec = mlgraph((3,22,12,1))
  26. net = ffnet(conec)

  27. # Read training data omitting first column and first line
  28. print "READING DATA..."
  29. data = readdata( 'data/black-scholes.dat',
  30.                  usecols  = (1, 2, 3, 4),
  31.                  skiprows =  1)
  32. input =  data[:, :3] #first 3 columns
  33. target = data[:, -1] #last column

  34. print "TRAINING NETWORK..."
  35. import sys; sys.stdout.flush() #Just to ensure dislpaing the above messages here
  36. net.train_tnc(input, target, maxfun = 5000, messages=1)

  37. # Test network
  38. print
  39. print "TESTING NETWORK..."
  40. output, regression = net.test(input, target, iprint = 0)
  41. Rsquared = regression[0][2]
  42. maxerr = abs( array(output).reshape( len(output) ) - array(target) ).max()
  43. print "R-squared:           %s  (should be >= 0.999999)" %str(Rsquared)
  44. print "max. absolute error: %s  (should be <= 0.05)" %str(maxerr)
  45. print
  46. print "Is ffnet ready for a stock?"

  47. #####################################
  48. # Make plot if matplotlib is avialble
  49. try:
  50.     from pylab import *
  51.     plot( target, 'b--' )
  52.     plot( output, 'k-' )
  53.     legend(('target', 'output'))
  54.     xlabel('pattern'); ylabel('price')
  55.     title('Outputs vs. target of trained network.')
  56.     grid(True)
  57.     show()
  58. except ImportError, e:
  59.     print "Cannot make plots. For plotting install matplotlib.\n%s" % e
复制代码


使用道具

报纸
Lisrelchen 发表于 2014-10-11 05:21:33 |只看作者 |坛友微信交流群
  1. ### Multiprocessing training example for ffnet ###

  2. from ffnet import ffnet, mlgraph
  3. from scipy import rand

  4. # Generate random training data (large)
  5. input = rand(10000, 10)
  6. target = rand(10000, 1)

  7. # Define net (large one)
  8. conec = mlgraph((10,300,1))
  9. net = ffnet(conec)

  10. # Test training speed-up
  11. # Note that the below *if* is necessary only on Windows
  12. if __name__=='__main__':   
  13.     from time import time
  14.     from multiprocessing import cpu_count
  15.    
  16.     # Preserve original weights
  17.     weights0 = net.weights.copy()
  18.    
  19.     print "TRAINING, this can take a while..."
  20.     for n in range(1, cpu_count()+1):
  21.         net.weights[:] = weights0  #Start always from the same point
  22.         t0 = time()
  23.         net.train_tnc(input, target, nproc = n, maxfun=50, messages=0)
  24.         t1 = time()
  25.         print '%s processes: %s s' %(n, t1-t0)
复制代码


使用道具

地板
狂热的爱好者 学生认证  发表于 2014-10-29 12:31:50 |只看作者 |坛友微信交流群
辛苦辛苦

使用道具

7
lonestone 在职认证  发表于 2019-4-19 15:26:46 |只看作者 |坛友微信交流群
感谢 分享

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-26 10:27