tensorflow鸢尾花
时间: 2025-02-17 16:11:40 浏览: 24
### TensorFlow 鸢尾花数据集示例
#### 加载鸢尾花数据集
为了使用 TensorFlow 进行鸢尾花数据集的操作,可以利用 `tf.keras.datasets` 来加载内置的数据集:
```python
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载鸢尾花数据集
iris, target = tf.keras.datasets.iris.load_data() # 假设此方法存在用于说明[^1]
# 数据预处理
X_train, X_temp, y_train, y_temp = train_test_split(iris, target, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
X_test = scaler.transform(X_test)
```
请注意,在实际环境中,可能需要通过其他库如 `sklearn.datasets` 或者手动下载 CSV 文件来获取该数据集。
#### 构建神经网络模型
构建一个多层感知机(MLP),并编译它以便后续训练:
```python
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(4,)),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
#### 训练模型
设置好批次大小和轮次数量之后就可以开始训练过程了:
```python
batch_size = 32
epochs = 100
history = model.fit(X_train, y_train,
validation_data=(X_val, y_val),
batch_size=batch_size,
epochs=epochs)
```
#### 测试模型性能
最后一步是对测试集上的表现进行评估:
```python
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
print(f'\nTest accuracy: {test_acc}')
```
阅读全文
相关推荐


















