【问题标题】:How to output dictionary of numpy arrays to file [duplicate]如何将numpy数组的字典输出到文件[重复]
【发布时间】:2018-09-05 13:24:06
【问题描述】:
from os import listdir
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg19 import preprocess_input
from keras.applications.vgg19 import decode_predictions
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.models import Model
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import numpy as np
import os
import time
import matplotlib.pyplot as plt
import csv
from pickle import dump
import xlsxwriter
from sklearn.feature_extraction import DictVectorizer
import pandas as pd   
import os
from openpyxl import load_workbook
import xlsxwriter
import pickle
# load an image from file
path1 = '/home/mclab/Desktop/Test'    #path of folder of images

# extract features from each photo in the directory
def extract_features(directory):
   # load the model
   model = VGG16()
   # re-structure the model
   model.layers.pop()
   model = Model(inputs=model.inputs, outputs=model.layers[-1].output)
   # summarize
   print(model.summary())
   # extract features from each photo
   features = dict()
   for name in listdir(directory):
      # load an image from file
      filename = directory + '/' + name
      image = load_img(filename, target_size=(224, 224))
      # convert the image pixels to a numpy array
      image = img_to_array(image)
      # reshape data for the model
      image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
      # prepare the image for the VGG model
      image = preprocess_input(image)
      # get features
      feature = model.predict(image, verbose=0)
      # get image id
      image_id = name.split('.')[0]
      # store feature
      features[image_id] = feature
      print('>%s' % name)
return features
# extract features from all images
directory = path1
features = extract_features(directory)
print('Extracted Features: %d' % len(features))
print (features)

我从给定目录中的数据中为 4 个输入图像运行此代码。我的字典是这种形式的
特征 = {'1': array([[0. , 4.845782 , 0. , ..., 2.6509986, 0. , 0. ]], dtype=float32), '3': 数组([[0. , 0.5562537, 0. , ..., 1.1013255, 0. , 0. ]], dtype=float32), '2': 数组([[0.11465299, 0., 3.7899919, ..., 0., 0., 0. ]], dtype=float32), '4': 数组([[0. , 0. , 0. , ..., 0. , 2.6636925, 0.]], dtype=float32)}

我注意到字典中的每个值都由关键图像的特征数组表示。我的问题是:如何将输入图像的特征数组保存在 excel 文件中,以便将这些特征用于回归问题。

【问题讨论】:

  • @Georgy,我认为dict 的结构实际上与您的副本非常不同。 OP 的字典实际上更容易处理,因为我们可以聚合到一个 numpy 数组中,这实际上是您在这种情况下应该执行的操作。
  • @jpp 除了链接帖子中的数据结构比较复杂之外,问题基本相同,所以我认为应该标记为重复。但我可能错了,这就是为什么它说“可能重复”。 :) 尽管如此,您的答案更适合这种特殊情况,并且绝对应该保留,这就是我赞成它的原因。
  • @Georgy,不是批评,我自己也经常犯同样的错误:)。我只是担心用户会去另一个帖子并尝试逐行编写。

标签: python arrays python-2.7 csv dictionary


【解决方案1】:

这是仅使用 numpy 功能保存到 CSV 的一种方法。 CSV 文件可以在 Excel 中打开。

该解决方案假定您要事先按键排序。请注意,字典不被认为是有序的。如果订购很重要,请考虑使用collections.OrderedDict

我提供了一个最小的示例,可以应用于任意大小的字典。

import numpy as np

# example dictionary input
d = {0: np.array([1, 2, 3, 4, 5]),
     1: np.array([6, 7, 8, 9, 10]),
     2: np.array([11, 12, 13, 14, 15])}

# build array from dictionary
arr = np.array([v for _, v in sorted(d.items())])

# array([[ 1,  2,  3,  4,  5],
#        [ 6,  7,  8,  9, 10],
#        [11, 12, 13, 14, 15]])

# save to array
np.savetxt('out.csv', arr, delimiter=',')

如果您真的需要保存为.xlsx 格式,可以通过 Pandas 进行:

pd.DataFrame(arr).to_excel('file.xlsx', index=False)

【讨论】:

  • 谢谢 jpp 我会试试的。实际上,在我的例子中,每个数组都代表图像的特征向量,例如 '1': array([[0., 4.845782, 0., ..., 2.6509986, 0., 0.]], dtype=float32) 是名为“1”的图像的特征向量。所以,我需要将每个图像的特征向量保存在一个 excel 文件中,然后我可以用于回归问题
  • @fatma,好的。我也通过 pandas 更新了 Excel 解决方案。
  • 对于行 np.savetxt('out.csv', arr, delimiter=',') 我得到 ValueError: Expected 1D or 2D array, got 3D array instead
  • @fatma,不知道为什么。您是否按原样尝试过上面的代码?我想确定这是否是您的输入/我的逻辑/不同环境的问题。
  • 这是我的输入字典的示例: {'1': array([[0. , 4.845782 , 0. , ..., 2.6509986, 0. , 0. ]], dtype= float32), '3': 数组([[0. , 0.5562537, 0. , ..., 1.1013255, 0. , 0. ]], dtype=float32), '2': 数组([[0.11465299, 0. , 3.7899919 , ..., 0. , 0. , 0. ]], dtype=float32), '4': array([[0. , 0. , 0. , ..., 0. , 2.6636925, 0 . ]], dtype=float32)}
猜你喜欢
  • 2017-10-07
  • 2016-03-05
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2014-05-18
相关资源
最近更新 更多