tensorflow鸢尾花分类 山鸢尾和维吉尼亚鸢尾
时间: 2024-01-20 10:14:48 浏览: 29
以下是使用TensorFlow实现鸢尾花分类的代码,可以区分山鸢尾和维吉尼亚鸢尾:
```python
import tensorflow as tf
import pandas as pd
# 读取数据集
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
train_path = tf.keras.utils.get_file(
"iris_training.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv")
test_path = tf.keras.utils.get_file(
"iris_test.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv")
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
train_y = train.pop('Species')
test_y = test.pop('Species')
# 构建特征列
my_feature_columns = []
for key in train.keys():
my_feature_columns.append(tf.feature_column.numeric_column(key=key))
# 构建分类器
classifier = tf.estimator.DNNClassifier(
feature_columns=my_feature_columns,
hidden_units=[30, 10],
n_classes=3)
# 训练模型
train_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(
x=train,
y=train_y,
batch_size=32,
num_epochs=None,
shuffle=True)
classifier.train(input_fn=train_input_fn, steps=2000)
# 评估模型
test_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(
x=test,
y=test_y,
batch_size=32,
num_epochs=1,
shuffle=False)
eval_result = classifier.evaluate(input_fn=test_input_fn)
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
# 预测新数据
new_samples = pd.DataFrame({
'SepalLength': [5.1, 5.9, 6.9],
'SepalWidth': [3.3, 3.0, 3.1],
'PetalLength': [1.7, 4.2, 5.4],
'PetalWidth': [0.5, 1.5, 2.1],
})
predict_input_fn = tf.compat.v1.estimator.inputs.pandas_input_fn(
x=new_samples,
num_epochs=1,
shuffle=False)
predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [SPECIES[prediction['class_ids'][0]] for prediction in predictions]
print(
"New Samples, Class Predictions: {}\n"
.format(predicted_classes))
```