python多层感知机进行分类乳腺癌数据集
时间: 2023-07-25 08:41:07 浏览: 222
好,针对您的问题,我可以给您提供以下的Python代码实现:
首先,我们需要导入以下的库:
```python
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
```
然后,我们可以通过以下的代码加载并预处理数据:
```python
data = load_breast_cancer()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
接下来,我们可以通过以下的代码构建多层感知机模型:
```python
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=64, activation='relu', input_shape=(X_train.shape[1],)),
tf.keras.layers.Dense(units=32, activation='relu'),
tf.keras.layers.Dense(units=1, activation='sigmoid')
])
```
其中,我们使用了两个隐藏层,分别包含64和32个神经元,激活函数为ReLU;输出层包含1个神经元,激活函数为sigmoid。
最后,我们可以通过以下的代码对模型进行编译和训练:
```python
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test))
```
在训练完成后,我们可以通过以下的代码对模型进行评估:
```python
test_loss, test_acc = model.evaluate(X_test, y_test)
print('Test accuracy:', test_acc)
```
完整代码如下:
```python
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
data = load_breast_cancer()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=64, activation='relu', input_shape=(X_train.shape[1],)),
tf.keras.layers.Dense(units=32, activation='relu'),
tf.keras.layers.Dense(units=1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test))
test_loss, test_acc = model.evaluate(X_test, y_test)
print('Test accuracy:', test_acc)
```
希望这个答案对您有所帮助!
阅读全文