实现了正弦曲线的拟合,即regression问题。

创建的模型单输入单输出,两个隐层分别为100、50个神经元。

在keras的官方文档中,给的例子多是关于分类的。因此在测试regression时,遇到了一些问题。总结来说,应注意以下几个方面:

1)训练数据需是矩阵型,这里的输入和输出是1000*1,即1000个样本;每个样本得到一个输出;

注意:训练数据的生成非常关键,首先需要检查输入数据和输出数据的维度匹配;

2)对数据进行规范化,这里用到的是零均值单位方差的规范方法。规范化方法对于各种训练模型很有讲究,具体参照另一篇笔记:http://blog.csdn.net/csmqq/article/details/51461696;

3)输出层的**函数选择很重要,该拟合的输出有正负值,因此选择tanh比较合适;

4)regression问题中,训练函数compile中的误差函数通常选择mean_squared_error。

5)值得注意的是,在训练时,可以将测试数据的输入和输出绘制出来,这样可以帮助调试参数。

6)keras中实现回归问题,返回的准确率为0。

[python] view plain copy
  1. # -*- coding: utf-8 -*-  
  2. """ 
  3. Created on Mon May 16 13:34:30 2016 
  4. @author: Michelle 
  5. """  
  6. from keras.models import Sequential      
  7. from keras.layers.core import Dense, Activation     
  8. from keras.optimizers import SGD  
  9. from keras.layers.advanced_activations import LeakyReLU  
  10. from sklearn import preprocessing  
  11. from keras.utils.visualize_plots import figures  
  12. import matplotlib.pyplot as plt  
  13. import numpy as np      
  14.     
  15. #part1: train data    
  16. #generate 100 numbers from -2pi to 2pi      
  17. x_train = np.linspace(-2*np.pi, 2*np.pi, 1000)  #array: [1000,]    
  18. x_train = np.array(x_train).reshape((len(x_train), 1)) #reshape to matrix with [100,1]  
  19. n=0.1*np.random.rand(len(x_train),1#generate a matrix with size [len(x),1], value in (0,1),array: [1000,1]    
  20. y_train=np.sin(x_train)+n  
  21.     
  22. #训练数据集:零均值单位方差  
  23. x_train = preprocessing.scale(x_train)  
  24. scaler = preprocessing.StandardScaler().fit(x_train)   
  25. y_train = scaler.transform(y_train)  
  26.   
  27. #part2: test data    
  28. x_test = np.linspace(-5,5,2000)    
  29. x_test = np.array(x_test).reshape((len(x_test), 1))  
  30. y_test=np.sin(x_test)  
  31.   
  32. #零均值单位方差  
  33. x_test = scaler.transform(x_test)  
  34. #y_test = scaler.transform(y_test)  
  35. ##plot testing data  
  36. #fig, ax = plt.subplots()  
  37. #ax.plot(x_test, y_test,'g')  
  38.   
  39. #prediction data  
  40. x_prd = np.linspace(-3,3,101)    
  41. x_prd = np.array(x_prd).reshape((len(x_prd), 1))  
  42. x_prd = scaler.transform(x_prd)  
  43. y_prd=np.sin(x_prd)  
  44. #plot testing data  
  45. fig, ax = plt.subplots()  
  46. ax.plot(x_prd, y_prd,'r')  
  47.   
  48. #part3: create models, with 1hidden layers      
  49. model = Sequential()      
  50. model.add(Dense(100, init='uniform', input_dim=1))      
  51. #model.add(Activation(LeakyReLU(alpha=0.01)))   
  52. model.add(Activation('relu'))  
  53.   
  54. model.add(Dense(50))      
  55. #model.add(Activation(LeakyReLU(alpha=0.1)))   
  56. model.add(Activation('relu'))  
  57.   
  58. model.add(Dense(1))      
  59. #model.add(Activation(LeakyReLU(alpha=0.01)))   
  60. model.add(Activation('tanh'))  
  61.   
  62. #sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)  
  63. model.compile(loss='mean_squared_error', optimizer="rmsprop", metrics=["accuracy"])  
  64. #model.compile(loss='mean_squared_error', optimizer=sgd, metrics=["accuracy"])  
  65.     
  66. #model.fit(x_train, y_train, nb_epoch=64, batch_size=20, verbose=0)     
  67. hist = model.fit(x_test, y_test, batch_size=10, nb_epoch=100, shuffle=True,verbose=0,validation_split=0.2)  
  68. #print(hist.history)  
  69. score = model.evaluate(x_test, y_test, batch_size=10)  
  70.   
  71. out = model.predict(x_prd, batch_size=1)  
  72. #plot prediction data  
  73.   
  74. ax.plot(x_prd, out, 'k--', lw=4)  
  75. ax.set_xlabel('Measured')  
  76. ax.set_ylabel('Predicted')  
  77. plt.show()  
  78. figures(hist)  

用keras创建拟合网络解决回归问题Regression

虚线是预测值,红色是输入值;

用keras创建拟合网络解决回归问题Regression

绘制误差值随着迭代次数的曲线函数是Visualize_plots.py,

1)将其放在C:\Anaconda2\Lib\site-packages\keras\utils下面。

2)在使用时,需要添加这句话:from keras.utils.visualize_plots import figures,然后在程序中直接调用函数figures(hist)。

垓函数的实现代码为:

[python] view plain copy
  1. # -*- coding: utf-8 -*-  
  2. """ 
  3. Created on Sat May 21 22:26:24 2016 
  4.  
  5. @author: Shemmy 
  6. """  
  7.   
  8. def figures(history,figure_name="plots"):  
  9.     """ method to visualize accuracies and loss vs epoch for training as well as testind data\n 
  10.         Argumets: history     = an instance returned by model.fit method\n 
  11.                   figure_name = a string representing file name to plots. By default it is set to "plots" \n 
  12.        Usage: hist = model.fit(X,y)\n              figures(hist) """  
  13.     from keras.callbacks import History  
  14.     if isinstance(history,History):  
  15.         import matplotlib.pyplot as plt  
  16.         hist     = history.history   
  17.         epoch    = history.epoch  
  18.         acc      = hist['acc']  
  19.         loss     = hist['loss']  
  20.         val_loss = hist['val_loss']  
  21.         val_acc  = hist['val_acc']  
  22.         plt.figure(1)  
  23.   
  24.         plt.subplot(221)  
  25.         plt.plot(epoch,acc)  
  26.         plt.title("Training accuracy vs Epoch")  
  27.         plt.xlabel("Epoch")  
  28.         plt.ylabel("Accuracy")       
  29.   
  30.         plt.subplot(222)  
  31.         plt.plot(epoch,loss)  
  32.         plt.title("Training loss vs Epoch")  
  33.         plt.xlabel("Epoch")  
  34.         plt.ylabel("Loss")    
  35.   
  36.         plt.subplot(223)  
  37.         plt.plot(epoch,val_acc)  
  38.         plt.title("Validation Acc vs Epoch")  
  39.         plt.xlabel("Epoch")  
  40.         plt.ylabel("Validation Accuracy")    
  41.   
  42.         plt.subplot(224)  
  43.         plt.plot(epoch,val_loss)  
  44.         plt.title("Validation loss vs Epoch")  
  45.         plt.xlabel("Epoch")  
  46.         plt.ylabel("Validation Loss")    
  47.         plt.tight_layout()  
  48.         plt.savefig(figure_name)  
  49.     else:  
  50.         print "Input Argument is not an instance of class History"  


讨论keras中实现拟合回归问题的帖子: https://github.com/fchollet/keras/issues/108

相关文章:

  • 2022-12-23
  • 2021-07-07
  • 2021-12-05
  • 2022-12-23
  • 2021-08-30
  • 2021-11-21
  • 2021-12-15
猜你喜欢
  • 2021-08-06
  • 2021-12-02
  • 2021-04-15
  • 2021-05-09
  • 2021-12-26
  • 2022-12-23
相关资源
相似解决方案