我想創建一個與cifar-10數據集具有相同格式的數據集,以便與Tensorflow一起使用。它應該有圖像和標籤。基本上,我希望能夠採用cifar-10代碼,但不同的圖像和標籤,並運行該代碼。我還沒有找到任何關於如何在線執行此操作的信息,而且對機器學習來說也是全新的。創建一個與cifar-10數據集格式相同的數據集
回答
CIFAR-10是一個更大的dataset的子集。您需要的圖像是具有三個顏色通道的高度和寬度爲32像素的縮放彩色圖像。實現目標的一種方法是從CIFAR-100數據集中選擇10個不同的標籤,保存並運行現有的代碼。例如,您可能想要選擇車輛1和車輛2超級類別。這將爲您提供6000張標籤圖像,內容包括:自行車,公共汽車,摩托車,皮卡車,火車,割草機,火箭,路面電車,坦克和拖拉機班。然後,您可以構建車輛類型的預測值 - 這對於更熟悉機器學習非常酷。 : - )
在cifar10.py文件中,您可以看到從'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'下載的用於訓練文件的目錄。無需更改任何代碼,只需使用數據更新這些虛增的培訓文件即可。看看/ tmp/cifar10_data/cifar-10-batches-bin目錄。例如。 batches.meta.txt文件包含如下「二進制版本」部分中所述的標籤:https://www.cs.toronto.edu/~kriz/cifar.html
我也必須這樣做,並且製作了一組函數來將圖像和文本文件格式化爲可讀格式爲tensorflow。這裏是我做了用一組圖像中一個文件夾,名爲圖像(我用的水珠通過他們迭代),並與有關編碼的圖像信息的文本文件的修改(我有一系列的數字爲每個圖像,其中,數字描述了在每次拍攝圖像時用戶指導機器人的位置)。我做了一個函數來生成minibatches,並創建一個訓練和測試數據集。我還將與每個圖像關聯的數字轉換爲一個熱點矢量以適應(如果需要,您可以使用它,但可能無用)。
#!/usr/bin/python
import cv2
import numpy as np
import tensorflow as tf
import glob
import re
import random
# Parameters
learning_rate = 0.001
training_iters = 20000
batch_size = 120
display_step = 10
# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 1 # MNIST total classes (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units
image = np.reshape(np.asarray(mnist.train.images[0]), (28,28))
#Process Images
cv_img = []
for img in glob.glob("./images/*.jpeg"):
n = cv2.cvtColor(cv2.resize(cv2.imread(img), (28,28)), cv2.COLOR_BGR2GRAY)
n = np.asarray(n)
n = np.reshape(n, n_input)
cv_img.append(n)
#Process File for angle, here we read the text line by line and make a list
with open("./images/allinfo.txt") as f:
content = f.readlines()
#Initialize arrays to unpack data file
angle = []
image_number = []
#Iterate through the text list and split each one by the comma separating the values.
#Turn the text into floats for use in the network
for i in range(len(content)):
content[i] = content[i][:-1].split(',')
image_number.append(float(content[i][1]))
angle.append(float(content[i][7]))
#Divide both angle and image number into test and train data sets
angle = np.atleast_2d(angle).T
##Encode angle into 10 classes (it ranges -1 to 1)
for i in range(len(angle)):
angle[i] = random.uniform(-1,1)
angle[i] = int((angle[i]+1.0)*n_classes/2.)
#Create a one-hot version of angle
angle_one_hot = np.zeros((len(angle),n_classes))
for c in range(len(angle)):
one_hot = np.zeros(n_classes)
one_hot[int(angle[c])] = 1
angle_one_hot[c] = one_hot
image_number = np.atleast_2d(image_number).T
test_data = np.hstack((image_number, angle))
#print test_data
train_percent = .8
train_number = int(len(test_data)*train_percent)
train_data = np.zeros((train_number, 2))
for i in range(train_number):
rand = random.randrange(0,len(test_data))
train_data[i] = test_data[rand]
test_data = np.delete(test_data, rand, 0)
test_data_images = test_data[:,0]
test_data_angles = test_data[:,1]
train_data_images, train_data_angles = train_data[:,0], train_data[:,1]
def gen_batch(angles, images, batch_size, image_array=cv_img):
indices = random.sample(xrange(0,len(images)), batch_size)
batch_images = []
batch_angles = []
# print angles
for i in range(batch_size):
batch_images.append(image_array[int(images[indices[i]])][:])
batch_angles.append(angles[indices[i]])
batch_images = np.asarray(batch_images)
batch_angles = np.asarray(batch_angles)
return batch_images, batch_angles
# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32)
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)
# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
# Create model
def conv_net(x, weights, biases, dropout):
# Reshape input picture
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# Convolution Layer
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
# Max Pooling (down-sampling)
conv1 = maxpool2d(conv1, k=2)
# Convolution Layer
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
# Max Pooling (down-sampling)
conv2 = maxpool2d(conv2, k=2)
# Fully connected layer
# Reshape conv2 output to fit fully connected layer input
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# Apply Dropout
fc1 = tf.nn.dropout(fc1, dropout)
# Output, class prediction
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
# Store layers weight & bias
weights = {
# 5x5 conv, 1 input, 32 outputs
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
# 5x5 conv, 32 inputs, 64 outputs
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bd1': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = conv_net(x, weights, biases, keep_prob)
# Define loss and optimizer
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
cost = tf.reduce_mean(pred)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize((pred-y)**2)
# Evaluate model
correct_pred = y
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initializing the variables
init = tf.initialize_all_variables()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
step = 1
print(y)
# Keep training until reach max iterations
while step * batch_size < training_iters:
batch_x, batch_y = gen_batch(train_data_angles, train_data_images, batch_size)
#cv2.imshow('trash', batch_x[0,:].reshape((28,28)))
#cv2.waitKey(0)
#print(batch_y)
# Run optimization op (backprop)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
keep_prob: dropout})
if step % display_step == 0:
# Calculate batch loss and accuracy
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y,
keep_prob: 1.})
print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc)
step += 1
print "Optimization Finished!"
# Calculate accuracy for all test images
img, lbls = gen_batch(test_data_angles, test_data_images, len(test_data_angles))
print "Testing Accuracy:", \
sess.run(accuracy, feed_dict={x: img,
y: lbls,
keep_prob: 1.})
這不會是一個很好的工作,NN(該數據不被標準化,學習率是兩頭高,並且訓練精度沒有設置),但圖像處理代碼工作。
希望這會有所幫助!
- 1. Spark數據集:表格數據與其創建的視圖不完全相同
- 2. 根據不同的數據集創建數據集
- 3. 創建不同的數據集數組
- 4. 從相同數據集中的2個表格之間的關係創建表或數據集
- 5. 使用不同格式的輸入值創建數據集
- 6. 如何創建一個數據集市
- 7. 導出不同格式的數據集
- 8. 格式化數據中的數據集
- 9. 創建數據合同程序集
- 10. 從數據集創建數據庫(mdf)
- 11. senseval 2數據集格式
- 12. Wapiti/CRF ++數據集格式
- 13. ZOS:創建數據集
- 14. Networkx數據集創建
- 15. SAS - 創建一個數據集,無論輸入數據集如何
- 16. 如何創建數據集的h5py數據集
- 17. 數據集檢索另一個數據集的數據
- 18. BIRT數據集爲每個項目打印相同的數據
- 19. 比較一個數據集與vb.net中的另一個數據集
- 20. 從數據集創建可用數據集
- 21. 從現有數據集中創建新數據集
- 22. SSRS來自一個數據集的數據不在另一個數據集
- 23. 格式問題與從數據集數據導入到Excel表
- 24. 爲多個數據集創建一個numpy數組
- 25. SQL均相同的數據集
- 26. 爲大型數據集創建MySQL數據庫模式
- 27. 在長格式數據集中創建%更改列
- 28. 調用數據集的一個子集
- 29. 遍歷位數來創建數據集
- 30. 如何給一組向量創建一個新的數據集?
你已經基本上說明你需要什麼:你需要找到與標籤一組新的圖像。你可以a)尋找一組現有的圖像和標籤,或b)下載你自己的圖像並自己貼上標籤。現有的60,000幅圖像(50,000列/ 10,000測試)不適合您的使用情況?這是開始執行計算機視覺的非常好的數據集。 – blacksite
給我們提供關於cifar-10數據集的更多信息,以便我們能夠幫助您創建相同的結構。他們不知道cifar-10數據集是如何構建的,他們沒有時間去查看它來幫助你。 – Feras