如何利用Tens模型进行预测

2024-05-14 19:44:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基于虹膜数据集进行预测的神经网络

names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'species']  
train = pd.read_csv(dataset, names=names, skiprows=1)  
test = pd.read_csv(test_dataset, names=names, skiprows=1)
Xtrain = train.drop("species" , axis = 1)
Xtest = train.drop("species" , axis = 1)

ytrain = pd.get_dummies(train.species)
ytest = pd.get_dummies(test.species)
def create_train_model(hidden_nodes, num_iters):

    # Reset the graph
    tf.reset_default_graph()

    # Placeholders for input and output data
    X = tf.placeholder(shape=(120, 4), dtype=tf.float64, name='X')
    y = tf.placeholder(shape=(120, 3), dtype=tf.float64, name='y')

    # Variables for two group of weights between the three layers of the network
    W1 = tf.Variable(np.random.rand(4, hidden_nodes), dtype=tf.float64)
    W2 = tf.Variable(np.random.rand(hidden_nodes, 3), dtype=tf.float64)

    # Create the neural net graph
    A1 = tf.sigmoid(tf.matmul(X, W1))
    y_est = tf.sigmoid(tf.matmul(A1, W2))

    # Define a loss function
    deltas = tf.square(y_est - y)
    loss = tf.reduce_sum(deltas)

    # Define a train operation to minimize the loss
    optimizer = tf.train.GradientDescentOptimizer(0.005)
    train = optimizer.minimize(loss)

    # Initialize variables and run session
    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)

    # Go through num_iters iterations
    for i in range(num_iters):
        sess.run(train, feed_dict={X: Xtrain, y: ytrain})
        loss_plot[hidden_nodes].append(sess.run(loss, feed_dict={X: Xtrain.as_matrix(), y: ytrain.as_matrix()}))
        weights1 = sess.run(W1)
        weights2 = sess.run(W2)

    print("loss (hidden nodes: %d, iterations: %d): %.2f" % (hidden_nodes, num_iters, loss_plot[hidden_nodes][-1]))
    sess.close()
    return weights1, weights2
# Plot the loss function over iterations
num_hidden_nodes = [5, 10, 20]  
loss_plot = {5: [], 10: [], 20: []}  
weights1 = {5: None, 10: None, 20: None}  
weights2 = {5: None, 10: None, 20: None}  
num_iters = 2000

plt.figure(figsize=(12,8))  
for hidden_nodes in num_hidden_nodes:  
weights1[hidden_nodes], weights2[hidden_nodes] = create_train_model(hidden_nodes, num_iters)
plt.plot(range(num_iters), loss_plot[hidden_nodes], label="nn: 4-%d-3" % hidden_nodes)

我想做一个预测,例如我将输入数组new_samples = np.array([[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=np.float32) 我知道dnnclasifier的存在,但我认为我必须改变我的代码来使用它。你能帮助我如何使用DnnClassifier或只是任何其他方式来作出预测,根据我的模型


Tags: therunnonenamesplottftrainnum
1条回答
网友
1楼 · 发布于 2024-05-14 19:44:06

首先,在关闭会话之前,我将变量保存在create\u train\u model中。你知道吗

  saver = tf.train.Saver()
  saver.save(sess,'my-model-' + str(hidden_nodes) )

然后在代码结束时恢复变量并运行会话

with tf.Session() as sess:
  saver = tf.train.Saver()
  saver.restore(sess, 'my-model-' + str(hidden_nodes) )
  y_est_val = sess.run(y_est, feed_dict={X: new_samples }

相关问题 更多 >

    热门问题