- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我训练这个模型来对数据集 Fashion-mnist 中的图像进行分类。当权重没有经过训练时,损失值看起来很正常,但是在第一个 epoch 之后,损失减少到 0,并且所有输入图像都被分类为 0 类。
如果添加正则化,权重更新速度会更慢,但最终会得到相同的结果,假设所有图像都分类为 0 类,损失值为 0。
import tensorflow as tf
from tensorflow import keras
import numpy as np
EPOCH = 10
BATCH_SIZE = 30
DATA_SIZE = 60000
REGULARIZER = 0.001
def main():
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.0
test_images = test_images / 255.0
train_labels = train_labels.reshape((60000, 1))
train_images = train_images.reshape((60000, 784))
test_images = test_images.reshape((10000, 784))
judge_labels = test_labels.reshape((10000, 1))
x = tf.placeholder(tf.float32, (None, 784))
y_ = tf.placeholder(tf.float32, (None, 1))
w1 = tf.Variable(np.random.rand(784 * 24).reshape([784, 24]) * 10, dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w1))
w2 = tf.Variable(np.random.rand(24 * 24).reshape([24, 24]) * 10, dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w2))
w3 = tf.Variable(np.random.rand(24 * 10).reshape([24, 10]) * 10, dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w3))
bias1 = tf.constant(1, shape=(24,), dtype=tf.float32)
bias2 = tf.constant(1, shape=(24,), dtype=tf.float32)
y1 = tf.nn.relu(tf.matmul(x, w1) + bias1)
y2 = tf.nn.relu(tf.matmul(y1, w2) + bias2)
y = tf.matmul(y2, w3)
predict = tf.argmax(y, axis=1)
y_spy = tf.nn.softmax(y, axis=1)
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_, 1), logits=y)
# loss = tf.reduce_mean(ce) + tf.add_n(tf.get_collection('losses'))
loss = tf.reduce_mean(ce)
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print('current out loss: ', end='')
print(sess.run(loss, feed_dict={x: test_images, y_: judge_labels}))
pre = sess.run(predict, feed_dict={x: test_images})
miss = pre - test_labels
print('right number: ', end='')
print((np.sum(miss == 0)))
for epoch in range(EPOCH):
for i in range(DATA_SIZE // BATCH_SIZE):
start = i * BATCH_SIZE
end = (i + 1) * BATCH_SIZE
_ = sess.run([train_step], feed_dict={x: train_images[start:end],
y_: train_labels[start:end]})
print('epochs %d :' % epoch)
print('current in loss: ', end='')
print(sess.run(loss, feed_dict={x: train_images[start:end],
y_: train_labels[start:end]}))
print('current out loss: ', end='')
print(sess.run(loss, feed_dict={x: test_images, y_: judge_labels}))
miss = sess.run(predict, feed_dict={x: test_images}) - test_labels
print('right number: ', end='')
print((np.sum(miss == 0)))
if __name__ == "__main__":
main()
最佳答案
错误1:损失函数应该是
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(y_, [-1]), logits=y)
因为标签是该损失函数的平坦值。 (将y占位符改为int32类型)
错误 2:权重被初始化为非常大的值。
GradientDescentOptimizer
是非常慢的优化器。使用 AdamOptimizer
代替
固定代码:
import tensorflow as tf
from tensorflow import keras
import numpy as np
EPOCH = 10
BATCH_SIZE = 64
DATA_SIZE = 60000
REGULARIZER = 0.001
def main():
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.0
test_images = test_images / 255.0
train_labels = train_labels.reshape((60000, 1))
train_images = train_images.reshape((60000, 784))
test_images = test_images.reshape((10000, 784))
judge_labels = test_labels.reshape((10000, 1))
x = tf.placeholder(tf.float32, (None, 784))
y_ = tf.placeholder(tf.int32, (None, 1))
w1 = tf.Variable(np.random.rand(784 * 24).reshape([784, 24]), dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w1))
w2 = tf.Variable(np.random.rand(24 * 24).reshape([24, 24]), dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w2))
w3 = tf.Variable(np.random.rand(24 * 10).reshape([24, 10]), dtype=tf.float32)
# tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w3))
bias1 = tf.constant(1, shape=(24,), dtype=tf.float32)
bias2 = tf.constant(1, shape=(24,), dtype=tf.float32)
y1 = tf.nn.relu(tf.matmul(x, w1) + bias1)
y2 = tf.nn.relu(tf.matmul(y1, w2) + bias2)
y = tf.matmul(y2, w3)
predict = tf.argmax(y, axis=1)
y_spy = tf.nn.softmax(y, axis=1)
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(y_, [-1]), logits=y)
# loss = tf.reduce_mean(ce) + tf.add_n(tf.get_collection('losses'))
loss = tf.reduce_mean(ce)
train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print('current out loss: ', end='')
print(sess.run(loss, feed_dict={x: test_images, y_: judge_labels}))
pre = sess.run(predict, feed_dict={x: test_images})
miss = pre - test_labels
print('right number: ', end='')
print((np.sum(miss == 0)))
for epoch in range(EPOCH):
for i in range(DATA_SIZE // BATCH_SIZE):
start = i * BATCH_SIZE
end = (i + 1) * BATCH_SIZE
_ = sess.run([train_step], feed_dict={x: train_images[start:end],
y_: train_labels[start:end]})
print('epochs %d :' % epoch)
print('current in loss: ', end='')
print(sess.run(loss, feed_dict={x: train_images[start:end],
y_: train_labels[start:end]}))
print('current out loss: ', end='')
print(sess.run(loss, feed_dict={x: test_images, y_: judge_labels}))
miss = sess.run(predict, feed_dict={x: test_images}) - test_labels
print('right number: ', end='')
print((np.sum(miss == 0)))
miss = sess.run(predict, feed_dict={x: test_images})
print (miss[0:10], test_labels[0:10])
if __name__ == "__main__":
main()
输出(选择性):
...
Sample predictions: [9 2 4 3 2 4 4 4 7 7], Actual: [9 2 1 1 6 1 4 6 5 7]
...
Sample predictions: [9 2 1 1 6 1 4 6 1 7], Actual: [9 2 1 1 6 1 4 6 5 7]
...
Sample predictions: [7 2 1 1 6 1 4 6 1 7], Actual: [9 2 1 1 6 1 4 6 5 7]
...
Sample predictions: [9 2 1 1 6 1 4 6 1 7], Actual: [9 2 1 1 6 1 4 6 5 7]
...
包含训练、验证损失和训练、验证准确性以及每个时期的洗牌训练数据的代码
import tensorflow as tf
from tensorflow import keras
import numpy as np
from sklearn.metrics import classification_report, accuracy_score
EPOCH = 30
BATCH_SIZE = 64
DATA_SIZE = 60000
REGULARIZER = 0.001
def main():
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.0
test_images = test_images / 255.0
train_labels = train_labels.reshape((60000, 1))
train_images = train_images.reshape((60000, 784))
test_images = test_images.reshape((10000, 784))
judge_labels = test_labels.reshape((10000, 1))
x = tf.placeholder(tf.float32, (None, 784))
y_ = tf.placeholder(tf.int32, (None, 1))
w1 = tf.Variable(np.random.rand(784 * 24).reshape([784, 24]), dtype=tf.float32)
tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w1))
w2 = tf.Variable(np.random.rand(24 * 24).reshape([24, 24]), dtype=tf.float32)
tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w2))
w3 = tf.Variable(np.random.rand(24 * 10).reshape([24, 10]), dtype=tf.float32)
tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(REGULARIZER)(w3))
bias1 = tf.constant(1, shape=(24,), dtype=tf.float32)
bias2 = tf.constant(1, shape=(24,), dtype=tf.float32)
y1 = tf.nn.relu(tf.matmul(x, w1) + bias1)
y2 = tf.nn.relu(tf.matmul(y1, w2) + bias2)
y = tf.matmul(y2, w3)
predict = tf.argmax(y, axis=1)
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(y_, [-1]), logits=y)
loss = tf.reduce_mean(ce)
train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
idx = np.arange(DATA_SIZE)
for epoch in range(EPOCH):
train_loss = list()
train_predict = list()
np.random.shuffle(idx)
train_images = train_images[idx]
train_labels = train_labels[idx]
for i in range(DATA_SIZE // BATCH_SIZE):
start = i * BATCH_SIZE
end = (i + 1) * BATCH_SIZE
_, loss_, p_ = sess.run([train_step, loss, predict], feed_dict={x: train_images[start:end],
y_: train_labels[start:end]})
train_loss.append(loss_)
train_predict.extend(p_)
test_loss, test_predict = sess.run([loss, predict], feed_dict={x: test_images,
y_: judge_labels})
print ("Epoch: {}, Train Loss: {:.3f}, Test Loss: {:.3f},"\
"Train Acc: {:.3f}, Test Acc: {:.3f}".format(
epoch+1, np.mean(train_loss), test_loss,
accuracy_score(train_labels[0:len(train_predict)], train_predict),
accuracy_score(judge_labels, test_predict)))
if __name__ == "__main__":
main()
输出:
....
Epoch: 27, Train Loss: 0.842, Test Loss: 1.015,Train Acc: 0.816, Test Acc: 0.798
Epoch: 28, Train Loss: 0.832, Test Loss: 0.880,Train Acc: 0.816, Test Acc: 0.806
Epoch: 29, Train Loss: 0.788, Test Loss: 0.886,Train Acc: 0.820, Test Acc: 0.805
Epoch: 30, Train Loss: 0.704, Test Loss: 0.742,Train Acc: 0.826, Test Acc: 0.815
关于python - 我的模型的损失值为 0,但它只是将所有输入分类到同一类,这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665888/
我打算使用 vulkan synchronization examples 之一作为如何处理不经常更新的统一缓冲区的引用。具体来说,我正在看这个: vkBeginCommandBuffer(...);
我对 git 的了解有限。 我已经从 master 创建了一个分支 B1,进行了一些编辑并提交到这个分支。 我想从 B1 创建另一个分支 B2,我在 B2 中进行了一些编辑 而且我还想提交 B2(包含
这是我做的 我创建了一个分支 abc。然后我创建了两个文本文件 one.txt 和 two.txt。然后我将它们提交到分支 abc。然后我从分支中删除文件 one.txt 并将这些更改提交到分支。 现
在我的主分支中,我得到了 2 个文件: file1.txt file2.txt 我从那里创建了名为 b1 的新分支。在b1中,我修改了file2.txt,不小心删除了file1.txt(从磁盘中,当我
我是 git 的新手。 我创建了一个分支,进行了更改,现在我想 merge 回 master 以使它们“永久化”。 所以我执行了 git merge 1.2 报告为已经是最新的,在 master 上执
我在一个新团队中,工作方式与我以前习惯的完全不同,我们在功能分支上工作,测试人员会在该功能分支上进行测试,然后我们会运行一个 jenkins 作业在该功能被测试签署时将该功能 merge 到开发中,根
我目前正在学习动态内存管理是如何工作的,更具体地说是 realloc 以及它是如何在函数中完成的。 在下面的程序中,我只是想尝试使用 malloc 在函数 a() 中分配一些数字,然后将它们传递给另一
在 Java 中如何从另一个线程分派(dispatch)回主 UI 线程?我正在使用带有 Runnable 的执行器在主 UI 线程之外做一些工作,并且我有一个接口(interface),以便可以通过
我在 git 中有一个项目,所有的事情都直接在 master 分支上完成,标签被用来标记代码的发布版本。我知道这并不理想,并且一直在查看 git 流程,例如:http://nvie.com/posts
我们有一个相当大的 GIT 存储库,我想删除从未 merge 回 master 的分支。 反过来也很好 - 一种列出在某个时候已 merge 到 master 中的所有分支的方法。 我希望首先获取一个
在 Swift 和 C 之间传递字符串时,我看到一些我不理解的行为。请考虑以下 Swift 函数: func demo() { print("\n\n\n\n")
我以前从未合作过,现在我发现自己需要与其他一些人分享这个项目,即使我将完成 90% 的开发工作。 我在 github 上有一个私有(private)仓库。我用 推送了我的初始源 git push or
我们的项目使用 Gitlab,我们有两个长期存在的分支:dev 和 master,类似于 Git Flow。我们正在使用“merge 提交”方法,它将在主分支中创建一个 merge 提交。 但是,由于
我对自定义 View 的绑定(bind)属性有疑问。该属性绑定(bind)到核心数据实体的 NSArrayController。 问题是这样的: 在我看来,我画了几个矩形。这些矩形的位置保存在核心数据
这对我来说似乎太棘手,无法正确执行此操作。 我有一个TreeMap ,我正在获取其中的子图: public static reqObj assignObj(reqObj vArg, i
我有以下 XAML: 所以,基本上我希望将其中一
我正在使用 Angular js 1.3.4 版本并使用 ui-select。 我正在将复杂的多级 JSON 对象数组绑定(bind)到此 ui-select,它工作正常。因此用户可以在此选择中选择任
我正在使用 WebAPI 构建 API,并且一直在使用 NLog 在整个堆栈中进行日志记录。我的 API 解决方案有两个主要项目,包括: 实现 Controller 和 webapi 东西的网站层本身
在 Git 中,给定 (1) 一个分支 A 和 (2) 一个在过去某个时间从 A 派生的分支 B,然后 merge 回 A,我如何才能找到现在 A 中起源于 B 的所有提交? 目的是确定现在在 A 中
假设我的 Controller 如下所示: public class myController { private MyCustomItem acte; ... // gett
我是一名优秀的程序员,十分优秀!