使用鸢尾花数据集写一段DBN三层分类的代码
时间: 2023-05-17 10:03:56 浏览: 85
以下是使用鸢尾花数据集写的DBN三层分类的代码:
```python
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 数据预处理
scaler = StandardScaler()
X = scaler.fit_transform(X)
y = np.eye(3)[y]
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义DBN模型
n_input = X_train.shape[1]
n_hidden1 = 64
n_hidden2 = 32
n_output = y_train.shape[1]
# 定义权重和偏置
weights = {
'w1': tf.Variable(tf.random.normal([n_input, n_hidden1])),
'w2': tf.Variable(tf.random.normal([n_hidden1, n_hidden2])),
'w3': tf.Variable(tf.random.normal([n_hidden2, n_output]))
}
biases = {
'b1': tf.Variable(tf.random.normal([n_hidden1])),
'b2': tf.Variable(tf.random.normal([n_hidden2])),
'b3': tf.Variable(tf.random.normal([n_output]))
}
# 定义前向传播函数
def forward(x):
layer1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['w1']), biases['b1']))
layer2 = tf.nn.sigmoid(tf.add(tf.matmul(layer1, weights['w2']), biases['b2']))
output = tf.nn.softmax(tf.add(tf.matmul(layer2, weights['w3']), biases['b3']))
return output
# 定义损失函数和优化器
learning_rate = 0.01
epochs = 1000
batch_size = 32
n_batches = X_train.shape[0] // batch_size
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
pred = forward(x)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 训练模型
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(epochs):
avg_cost = 0
for i in range(n_batches):
batch_x, batch_y = X_train[i*batch_size:(i+1)*batch_size], y_train[i*batch_size:(i+1)*batch_size]
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
avg_cost += c / n_batches
if epoch % 100 == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
print("Optimization Finished!")
# 测试模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: X_test, y: y_test}))
```
希望这段代码能够帮助你!
阅读全文