gpt4 book ai didi

tensorflow - Keras 与 TensorFlow 代码比较源

转载 作者:行者123 更新时间:2023-12-02 14:48:44 26 4
gpt4 key购买 nike

这实际上不是特定于代码的问题,但我找不到任何答案或资源。

我目前正在尝试自学一些“纯”TensorFlow,而不仅仅是使用 Keras,我觉得如果有一些来源同时包含 TensorFlow 代码和等效的 Keras 代码,那将会非常有帮助-边进行比较。

不幸的是,我在 Internet 上找到的大多数结果都谈论性能方面的差异或有非常简单的比较示例(例如“所以这就是 Keras 使用起来更简单的原因”)。我对这些细节的兴趣不如对代码本身的兴趣。

有人知道是否有任何资源可以帮助解决这个问题吗?

最佳答案

这里有两个模型,分别在 TensorflowKeras 中,它们是对应的:

import tensorflow as tf
import numpy as np
import pandas as pd
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

tensorflow

X = tf.placeholder(dtype=tf.float64)
Y = tf.placeholder(dtype=tf.float64)
num_hidden=128

# Build a hidden layer
W_hidden = tf.Variable(np.random.randn(784, num_hidden))
b_hidden = tf.Variable(np.random.randn(num_hidden))
p_hidden = tf.nn.sigmoid( tf.add(tf.matmul(X, W_hidden), b_hidden) )

# Build another hidden layer
W_hidden2 = tf.Variable(np.random.randn(num_hidden, num_hidden))
b_hidden2 = tf.Variable(np.random.randn(num_hidden))
p_hidden2 = tf.nn.sigmoid( tf.add(tf.matmul(p_hidden, W_hidden2), b_hidden2) )

# Build the output layer
W_output = tf.Variable(np.random.randn(num_hidden, 10))
b_output = tf.Variable(np.random.randn(10))
p_output = tf.nn.softmax( tf.add(tf.matmul(p_hidden2, W_output), b_output) )

loss = tf.reduce_mean(tf.losses.mean_squared_error(
labels=Y,predictions=p_output))
accuracy=1-tf.sqrt(loss)
minimization_op = tf.train.AdamOptimizer(learning_rate=0.01).minimize(loss)

feed_dict = {
X: x_train.reshape(-1,784),
Y: pd.get_dummies(y_train)
}
with tf.Session() as session:
session.run(tf.global_variables_initializer())

for step in range(10000):
J_value = session.run(loss, feed_dict)
acc = session.run(accuracy, feed_dict)
if step % 100 == 0:
print("Step:", step, " Loss:", J_value," Accuracy:", acc)

session.run(minimization_op, feed_dict)
pred00 = session.run([p_output], feed_dict={X: x_test.reshape(-1,784)})

凯拉斯

import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from keras.models import Model

l = tf.keras.layers

model = tf.keras.Sequential([
l.Flatten(input_shape=(784,)),
l.Dense(128, activation='relu'),
l.Dense(128, activation='relu'),
l.Dense(10, activation='softmax')
])

model.compile(loss='categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])

model.summary()

model.fit(x_train.reshape(-1,784),pd.get_dummies(y_train),nb_epoch=15,batch_size=128,verbose=1)

关于tensorflow - Keras 与 TensorFlow 代码比较源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57273888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com