- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试使用 tensorflow 1.4.0 对我的原始记录进行分类。过程如下。
拳头:读取图片和标签,输出“tfrecord”格式的文件。第二:读取tf记录和训练
编写tfrecord脚本是
!/usr/bin/env python3
#coding:utf-8
import argparse
import os
import random
import numpy as np
from PIL import Image
import tensorflow as tf
def make_example(label_index, image):
return tf.train.Example(features = tf.train.Features(feature={
'label_index': tf.train.Feature(int64_list=tf.train.Int64List(value=[label_index])),
'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image]))
}))
def write_tfrecord(dataset, outputfilepath):
writer = tf.python_io.TFRecordWriter(outputfilepath)
for label_of_one_hot, image in dataset:
ex = make_example(label_of_one_hot, image)
writer.write(ex.SerializeToString())
writer.close()
def importingargs():
parser = argparse.ArgumentParser("tensorflow exampe")
parser.add_argument("--datafolderpath", "-df", help="datafolderpath")
parser.add_argument("--filepath", "-f", help="filepath", required=True)
parser.add_argument("--labelfilepath", "-lf", help="label filepath")
parser.add_argument("--outputfolderpath", "-of", help="outputfolderpath of tf records")
parser.add_argument("--seed", "-s", type=int, required=False, default=0)
args = parser.parse_args()
return args.filepath, args.datafolderpath, args.labelfilepath, args.outputfolderpath, args.seed
def load_data(filepath, datafolderpath, labelfilepath):
with open(labelfilepath, "r") as rf:
labellist = [ line.strip() for line in rf.readlines() ]
with open(filepath, "r") as rf:
filepathlist = [ line.strip() for line in rf.readlines() ]
alldatasets = list()
for filepath in filepathlist:
imagefilepath = os.path.join(datafolderpath, filepath)
# image = open(imagefilepath).read()
img_obj = Image.open(imagefilepath).convert("L")
img = np.array(img_obj)
w, h = img.shape
print(w, h)
print(w*h)
img = img.reshape(w*h).tostring()
print(type(img))
filename = filepath.split(os.path.sep)[-1]
label = filename.split(".")[0].split("_")[1]
index = labellist.index(label) +1
print(index)
alldatasets.append([ index, img ])
return alldatasets
def splitdata(datasets):
random.shuffle(datasets)
train_indexes = [ 0, int(len(datasets) * 0.8 ) ]
valid_indexes = [ train_indexes[-1], int(len(datasets) * 0.9 ) ]
test_indexes = [ valid_indexes[-1], int(len(datasets)) ]
train_data = datasets[train_indexes[0]:train_indexes[1]]
valid_data = datasets[valid_indexes[0]:valid_indexes[1]]
test_data = datasets[test_indexes[0]:test_indexes[1]]
print("train num: %d" % len(train_data))
print("test num: %d" % len(test_data))
print("valid num: %d" % len(valid_data))
return train_data, valid_data, test_data
def main():
filepath, datafolderpath, labelfilepath, outputfolderpath, seed = importingargs()
random.seed(seed)
alldatasets = load_data(filepath, datafolderpath, labelfilepath)
train_data, valid_data, test_data = splitdata(alldatasets)
train_outputfilepath = os.path.join(outputfolderpath, "train.tfrecord")
valid_outputfilepath = os.path.join(outputfolderpath, "valid.tfrecord")
test_outptufilepath = os.path.join(outputfolderpath, "test.tfrecord")
write_tfrecord(train_data, train_outputfilepath)
write_tfrecord(valid_data, valid_outputfilepath)
write_tfrecord(test_data, test_outptufilepath)
if __name__ == "__main__":
main()
导入train.py的load_dataset文件
#!/usr/bin/env python3
#coding:utf-8
import argparse
import os
import numpy as np
from PIL import Image
import tensorflow as tf
def read_tfrecord(inputfilepath):
print("read record")
reader = tf.TFRecordReader()
filename_que = tf.train.string_input_producer([inputfilepath])
key, value = reader.read(filename_que)
features = tf.parse_single_example(value,features = {
'label_index': tf.FixedLenFeature([], tf.string),
'image': tf.FixedLenFeature([], tf.string)
})
images = tf.decode_raw(features['image'], tf.float32)
images.set_shape([32*32])
images = tf.cast(images, tf.float32) * (1. / 255)
# images = tf.reshape(images, [-1])
labels = tf.decode_raw(features['label_index'], tf.int32)
# labels = tf.cast(features['label_index'], tf.int64)
# labels.set_shape([5])
print("call one hot")
label_index_one_hot = tf.one_hot(labels, 5)
label_index_one_hot.set_shape([5])
return images, label_index_one_hot
训练脚本是
import os
import random
import tensorflow as tf
import load_datasets
import datasets
import make_datasets
print("def input and output")
images = tf.placeholder(tf.float32, shape=[None, 32*32])
labels = tf.placeholder(tf.int32, shape=[None, 5])
print("def layers")
x = tf.placeholder(tf.float32, [ None, 32*32 ])
y_ = tf.placeholder(tf.float32, [None, 5 ])
# W1 = tf.Variable(tf.zeros([ 32*32, 500 ]))
# b1 = tf.Variable(tf.zeros([ 500 ]))
# W2 = tf.Variable(tf.zeros([ 500, 5 ]))
# b2 = tf.Variable(tf.zeros([ 5 ]))
print("def function")
# h1 = tf.matmul(x, W1) + b1
# y = tf.matmul(h1, W2) + b2
W = tf.Variable(tf.zeros([ 32*32, 5 ]))
b = tf.Variable(tf.zeros([ 5 ]))
y = tf.matmul(x, W) + b
print("def leraning model")
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
correct_prediction= tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("load train dataset")
trainfilepath = "../03tfrecords/train.tfrecord"
images, labels = load_datasets.read_tfrecord(trainfilepath)
input_queue = tf.train.slice_input_producer( [images, labels ], num_epochs=10, shuffle=False )
image_batch, label_batch = tf.train.batch( [images, labels], batch_size=10)
print("load test dataset")
testfilepath = "../03tfrecords/test.tfrecord"
test_image, test_label = load_datasets.read_tfrecord(testfilepath)
img_test_batch, label_test_batch = tf.train.batch([test_image,test_label],batch_size=16)
with tf.Session() as sess:
print("init layer value")
sess.run(tf.global_variables_initializer())
print("start training")
tf.train.start_queue_runners(sess)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
while not coord.should_stop():
for i in range(0, 10):
print("train num %d" % (i+1))
imgs, labels = sess.run([image_batch, label_batch])
sess.run(train_step, feed_dict={x:imgs, y_: labels})
imgs_test, labels_text = sess.run([img_test_batch, label_test_batch])
print(sess.run(accuracy, feed_dict={x:imgs_test, y_:labels_text}))
finally:
coord.request_stop()
coord.join(threads)
制作tfrecords效果很好,但是在训练脚本中,出现错误。
Traceback (most recent call last):
File "/home/omori/.pyenv/versions/tensorflow-py3/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 576, in merge_with
self.assert_same_rank(other)
File "/home/omori/.pyenv/versions/tensorflow-py3/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 621, in assert_same_rank
other))
ValueError: Shapes (?, 5) and (5,) must have the same rank
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "train.py", line 45, in <module>
images, labels = load_datasets.read_tfrecord(trainfilepath)
File "/home/omori/tensorflow_example/01src/load_datasets.py", line 30, in read_tfrecord
label_index_one_hot.set_shape([5])
File "/home/omori/.pyenv/versions/tensorflow-py3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 407, in set_shape
self._shape = self._shape.merge_with(shape)
File "/home/omori/.pyenv/versions/tensorflow-py3/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 582, in merge_with
raise ValueError("Shapes %s and %s are not compatible" % (self, other))
ValueError: Shapes (?, 5) and (5,) are not compatible
我搜索了很多网站,但找不到解决方案。我该如何解决?
最佳答案
Returns:
A Tensor of type out_type. A Tensor with one more dimension than the input bytes. The added
dimension will have size equal to the length of the elements of bytes divided by the number
of bytes to represent out_type.
所以在你的 read_tfrecord
函数中有一行
labels = tf.decode_raw(features['label_index'], tf.int32)
给 labels
一个额外的尺寸。您可以使用
label_index_one_hot = tf.one_hot(labels[0], 5)
(注意添加的[0]
)
我不得不承认,我不明白添加的维度是干什么用的。
关于tensorflow 错误 "raise ValueError("形状 %s 和 %s 不兼容"% (self, other)) ValueError : Shapes (? , 5) and (5,) are not compatible",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482082/
让我们写一个简单的类在我的脑海中解释: class SomeClass { var happyToUsed = 10 } 并创建一个对象 let someObject = SomeClass(
采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别? 例如 impl SomeStruct { fn example1(self) { } fn ex
请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 se
backbone.js 开始于: //Establish the root object, `window` (`self`) in the browser, or `global` on the s
做的事: self = self.init; return self; 在 Objective-C 中具有相同的效果: self.init() 快速? 例如,在这种情况下: else if([form
我查看了关于堆栈溢出的一些关于使用[weak self]和[unowned self]的问题的评论。我需要确保我理解正确。 我正在使用最新的 Xcode - Xcode 13.4,最新的 macOS
我面临在以下模型类代码中的 self.init 调用或分配给 self 之前使用 self 的错误tableview单元格项目,它发生在我尝试获取表格单元格项目的文档ID之后。 应该做什么?请推荐。
晚上好。 我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。 有一个示例函数。 func exampleFunction() { functionWithEsca
我需要在内心深处保持坚强的自我。 我知道声明[weak self]就够了外封闭仅一次。 但是guard let self = self else { return }呢? ,是否也足以为外部闭包声明一
代码 use std::{ fs::self, io::self, }; fn rmdir(path: impl AsRef) -> io::Result { fs::remo
我检查了共享相同主题的问题,但没有一个解决我遇到的这种奇怪行为: 说我有一个简单的老学校struct : struct Person { var name: String var age:
我应该解释为什么我的问题不是重复的:TypeError: can only concatenate list (not “str”) to list ...所以它不是重复的,因为该帖子处理代码中出现的
我有一个 trait,它接受一个类型参数,我想说实现这个 trait 的对象也会符合这个类型参数(使用泛型,为了 Java 的兼容性) 以下代码: trait HandleOwner[SELF
这个问题在这里已经有了答案: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 个答案) 关闭 8
我总是找到一些类似的代码newPromise.promiseDispatch.apply(newPromise, message),我不明白为什么不使用newPromise.promiseDispat
我看到类似的模式 def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... 非
mysql查询示例: SELECT a1.* FROM agreement a1 LEFT JOIN agreement a2 on a1.agreementType = a2.agreementTy
self.delegate = self; 这样做有什么问题吗?正确的做法是什么? 谢谢,尼尔。 代码: (UITextField*)initWith:(id)sender:(float)X:(flo
为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。
这个问题已经有答案了: What does the ampersand (&) before `self` mean in Rust? (1 个回答) 已关闭去年。 我不清楚 self 之间有什么区别
我是一名优秀的程序员,十分优秀!