BP人工神经网络案例

#BP人工神经网络实现
#1.读取数据
#2.导入keras.models Sequential  /keras.layers.core Dense,Activation
#3.Squential 建立模型
#4.Dense 建立层
#5.Activation激活函数
#6.compile模型编译
#7.fit训练(学习)
#8.验证(测试,分类预测)
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers.core import Dense,Activation
dataframe=pd.read_csv("路径文件",encoding="gbk")
#print(dataframe)
x=dataframe.ix[:,1:5].as_matrix()
y=dataframe.ix[:,5].as_matrix()
for i in range(0,len(x)):
    for j in range(0,len(x[i])):
        if (x[i][j]=="是" or x[i][j]=="多"):
            x[i][j]=1
        else:
            x[i][j]=0
for i in range(0,len(y)):
    if (y[i]=="高"):
        y[i]=1
    else:
        y[i]=0
#建立模型
model=Sequential()
#输入层
model.add(Dense(10,input_dim=len(x[0])))
model.add(Activation("relu"))#激活函数为relu
#输出层
model.add(Dense(1,input_dim=1))
model.add(Activation("sigmoid"))#激活函数为sigmoid
#模型编译
model.compile(optimizer="adam",loss="binary_crossentropy")#损失函数设为binary_crossentropy
#模型训练
model.fit(x,y,epochs=1000,batch_size=100)#训练1000次
#预测
final=model.predict_classes(x)
#算正确率
t=0
for i in range(0,len(final)):
    if(final[i]==y[i]):
        t+=1
print(t/len(x))



你可能感兴趣的:(python)