MLP实现非线性二分类 keras简单应用

import pandas as pd
import numpy as np
data = pd.read_csv("MLP_test_data.csv")
data.head()

在这里插入图片描述
数据自己用excel生成的…
再处理一下输出:

print(type(data),type(data.loc[:,'x']))
data_x = []
data_y = []
data_lable = []
for index, row  in data.iterrows():
    # print(type(row),row['x'],row['y'])
    data_x.append(row['x'])
    data_y.append(row['y'])
    if(row['x'] < 5 and row['y'] >5):
        data_lable.append(1)
    elif(row['x'] > 5 and row['y'] <5):
        data_lable.append(1)
    elif(row['x'] <5 and row['y'] <5):
        data_lable.append(0)
    elif(row['x'] >5 and row['y'] >5):
        data_lable.append(0)
    else:
        data_lable.append(2)
    pass
# res = pd.Series(data,index=["d","c","b","a"])
print(data_x)
print(data_lable)

data_new = {
        'x1':data_x,
        'x2':data_y,
        'y':data_lable}
df = pd.DataFrame(data_new)
df.head()

在这里插入图片描述

X = df.drop(['y'],axis=1)
y = df.loc[:,'y']
y.head()
%matplotlib inline
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.title("raw data")
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()

在这里插入图片描述

#分离样本
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)

(236, 2) (117, 2) (353, 2)

#构建模型
from keras.models import Sequential
from keras.layers import Dense,Activation
mlp = Sequential()
mlp.add(Dense(units=20,input_dim=2,activation="sigmoid"))#20个神经元 激活函数digmoid
mlp.add(Dense(units=1,activation="sigmoid"))
mlp.summary()

在这里插入图片描述

#配置模型参数
#优化方法 损失函数
mlp.compile(optimizer="adam",loss="binary_crossentropy")#二分类的
#模型训练
mlp.fit(X_train,y_train,epochs=3000)#迭代次数

在这里插入图片描述迭代3000次

#预测 训练集 准确率
y_train_predict = mlp.predict_classes(X_train)
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_train,y_train_predict)
print(accuracy)

0.9449152542372882

#预测 测试数据集
y_test_predict = mlp.predict_classes(X_test)
accuracy = accuracy_score(y_test,y_test_predict)
print(accuracy)

0.9145299145299145

y_train_predict_form = pd.Series(i[0] for i in y_train_predict)
print(y_train_predict_form)

#画图的点集
xx , yy = np.meshgrid(np.arange(0,10,0.1),np.arange(0,10,0.1))
x_range = np.c_[xx.ravel(),yy.ravel()]
y_range_predict = mlp.predict_classes(x_range)
print(type(y_range_predict))

#转换格式
y_range_predict_form = pd.Series(i[0] for i in y_range_predict )
%matplotlib inline
fig2 = plt.figure(figsize=(5,5))
passed_predict = plt.scatter(x_range[:,0][y_range_predict_form == 1],x_range[:,1][y_range_predict_form == 1])
failed_predict = plt.scatter(x_range[:,0][y_range_predict_form == 0],x_range[:,1][y_range_predict_form == 0])

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_predict,failed_predict),("passed","failed","passed_predict","failed_predict"))
plt.title("prediction data")
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()

在这里插入图片描述

好的,这是一个基本的二分类任务,我们可以使用多种深度学习模型来解决这个问题,比如神经网络、卷积神经网络、循环神经网络等等。在这里,我将介绍一种简单但有效的模型——多层感知机(Multilayer Perceptron,MLP)。 MLP是一种前馈神经网络,它由多个全连接层组成。每个全连接层都由一组神经元组成,它们将输入信号映射到输出信号。MLP中的每个神经元都与前一层中的所有神经元相连,因此,MLP能够学习复杂的非线性函数。 下面是使用PythonKeras实现二分类任务的简单代码: ```python import numpy as np from keras.models import Sequential from keras.layers import Dense # 生成数据 np.random.seed(0) X = np.random.rand(1000, 10) y = np.random.randint(2, size=(1000, 1)) # 定义模型 model = Sequential() model.add(Dense(32, input_dim=10, activation='relu')) model.add(Dense(1, activation='sigmoid')) # 编译模型 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(X, y, epochs=10, batch_size=32) # 评估模型 loss, accuracy = model.evaluate(X, y) print('Loss:', loss) print('Accuracy:', accuracy) ``` 在这个代码中,我们首先使用Numpy生成了一个形状为(1000, 10)的随机数输入矩阵X和一个形状为(1000, 1)的随机数标签矩阵y。然后,我们使用Keras创建了一个包含一个输入层、一个隐藏层和一个输出层的MLP模型。其中,输入层有10个神经元,隐藏层有32个神经元,输出层有1个神经元。最后,我们使用二元交叉熵作为损失函数,Adam优化器作为优化算法,训练模型并评估其性能。 这个任务并不需要很深的网络模型,MLP就能够很好地解决它。当然,如果你有更复杂的任务,可能需要使用更深的神经网络模型。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickdlk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值