keras 实现BP神经网络
生活随笔
收集整理的這篇文章主要介紹了
keras 实现BP神经网络
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 09:59:50 2017@author: Administrator
"""import pandas as pd
inputfile = 'input.xlsx' #excel輸入
outputfile = 'output.xls' #excel輸出
modelfile = 'modelweight.model' #神經(jīng)網(wǎng)絡權重保存
data = pd.read_excel(inputfile,index='Date',sheetname=0) #pandas以DataFrame的格式讀入excel表
feature = ['F1','F2','F3','F4'] #影響因素四個
label = ['L1'] #標簽一個,即需要進行預測的值
data_train = data.loc[range(0,20)].copy() #標明excel表從第0行到520行是訓練集#2 數(shù)據(jù)預處理和標注
data_mean = data_train.mean()
data_std = data_train.std()
data_train = (data_train - data_mean)/data_std #數(shù)據(jù)標準化
x_train = data_train[feature].as_matrix() #特征數(shù)據(jù)
y_train = data_train[label].as_matrix() #標簽數(shù)據(jù)#3 建立一個簡單BP神經(jīng)網(wǎng)絡模型
from keras.optimizers import SGD,adamfrom keras.models import Sequential
from keras.layers.core import Dense, Activation
model = Sequential() #層次模型
model.add(Dense(12,input_dim=4,init='uniform')) #輸入層,Dense表示BP層
model.add(Activation('relu')) #添加激活函數(shù)
model.add(Dense(1,input_dim=12)) #輸出層
model.compile(loss='mean_squared_error', optimizer='adam') #編譯模型
model.fit(x_train, y_train, nb_epoch = 1000, batch_size = 6) #訓練模型1000次
model.save_weights(modelfile) #保存模型權重#4 預測,并還原結果。
x = ((data[feature] - data_mean[feature])/data_std[feature]).as_matrix()
data[u'L1_pred'] = model.predict(x) * data_std['L1'] + data_mean['L1']#5 導出結果
data.to_excel(outputfile) #6 畫出預測結果圖
import matplotlib.pyplot as plt
p = data[['L1','L1_pred']].plot(subplots = True, style=['b-o','r-*'])
plt.show()
總結
以上是生活随笔為你收集整理的keras 实现BP神经网络的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 非线性方程组
- 下一篇: 递归神经网络预测股票好文章