使用python实现多层感知机分类器
以下是一个简单的多层感知机分类器的Python实现。
首先,我们需要导入必要的库:numpy、pandas和sklearn。
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
接下来,我们读取我们的数据集并进行预处理。在这个例子中,我们将使用一个名为“iris”的经典数据集。
# Load the dataset
iris = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
# Split the dataset into features and labels
X = iris.iloc[:, :-1].values
y = iris.iloc[:, -1].values
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Scale the features
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Encode the labels
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y_train = le.fit_transform(y_train)
y_test = le.transform(y_test)
现在我们可以开始构建我们的多层感知机模型。我们将使用Keras库来构建模型。
from keras.models import Sequential
from keras.layers import Dense
# Define the model
model = Sequential()
model.add(Dense(units=16, activation='relu', input_dim=4))
model.add(Dense(units=3, activation='softmax'))
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)
# Evaluate the model
test_loss, test_acc = model.evaluate(X_test, y_test)
print('Test accuracy:', test_acc)
我们的模型使用一个具有16个隐藏神经元的隐藏层,一个输出层和一个softmax激活函数。我们使用adam优化器和稀疏分类交叉熵损失函数来编译模型。最后,我们用训练集拟合模型并在测试集上评估模型的性能。
完整代码如下:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder
# Load the dataset
iris = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
# Split the dataset into features and labels
X = iris.iloc[:, :-1].values
y = iris.iloc[:, -1].values
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Scale the features
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Encode the labels
le = LabelEncoder()
y_train = le.fit_transform(y_train)
y_test = le.transform(y_test)
# Define the model
model = Sequential()
model.add(Dense(units=16, activation='relu', input_dim=4))
model.add(Dense(units=3, activation='softmax'))
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)
# Evaluate the model
test_loss, test_acc = model.evaluate(X_test, y_test)
print('Test accuracy:', test_acc)
原文地址: https://www.cveoy.top/t/topic/BrB 著作权归作者所有。请勿转载和采集!