文章目录
一、MLP是什么?
示例:MLP是多层感知器,是深度学习中的重要内容。
二、实例演示
1.引入库
首先先将数据加载进来
代码如下 :
import pandas as pd
import numpy as np
data = pd.read_csv('data.csv')
2.分类图形可视化
代码如下 :
#define the X and y
X = data.drop(['y'],axis=1)
y = data.loc[:,'y']
from matplotlib import pyplot as plt
fig1 = plt.figure(figsize=(5,5))
passed=plt.scatter(X.loc[:,'x1'][y==1],X.loc[:,'x2'][y==1])
failed=plt.scatter(X.loc[:,'x1'][y==0],X.loc[:,'x2'][y==0])
plt.legend((passed,failed),('passed','failed'))
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('raw data')
plt.show()
3.分离数据
代码如下 :
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.33,random_state=10)
print(X_train.shape,X_test.shape,X.shape)
4.建立模型
这里需要引入一个新的库keras
代码如下 :
from keras.models import Sequential
from keras.layers import Dense, Activation
mlp = Sequential()
mlp.add(Dense(units=20, input_dim=2, activation='sigmoid'))
mlp.add(Dense(units=1,activation='sigmoid'))
mlp.summary()
mlp.compile(optimizer='adam',loss='binary_crossentropy')
5.训练模型
代码如下 :
mlp.fit(X_train,y_train,epochs=3000)
6.对数据进行预测并计算精确度
y_train_predict = mlp.predict_classes(X_train)
from sklearn.metrics import accuracy_score
accuracy_train = accuracy_score(y_train,y_train_predict)
print(accuracy_train)