在Python机器学习中,如何读取CSV数据呢,可以通过cvs或者pandas两种方式读取。
def Load_csv(csv_file_name="test.csv"):
"""
从CSV文件中读取数据信息
:param csv_file_name: CSV文件名
:return: Data:二维数组
"""
import csv
csv_reader = csv.reader(open(csv_file_name))
Data=[]
for row in csv_reader:
Data.append(row)
print("Read All!")
return Data
def get_mnist_test_data():
"""label 在前,相应的参数可以根据实际需求更改"""
import pandas as pd
import numpy as np
data = pd.read_csv('Train.csv')
images = data.iloc[:,1:].values
labels = data.iloc[:,:1].values.ravel()
images = np.multiply(images,1.0/255.0)
images = images.reshape(images.shape[0],1,28,28)
# print(images)
return images,labels
def get_mnist_test_data1():
"""label在后,相应的参数可以根据实际需求更改"""
import pandas as pd
import numpy as np
data = pd.read_csv('Train.csv')
images = data.iloc[:,0:784].values
labels = data.iloc[:,784:785].values.ravel()
images = np.multiply(images,1.0/255.0)
images = images.reshape(images.shape[0],1,28,28)
return images,labels
如何将文件中的图像数据存储成CSV文件呢?通过数据把图像数据.append到数组中,然后通过CSV将数组中的数据下入CSV文件。
def Write_csv(Data=[[None]],csv_file_name="Train.csv"):
"""
向CSV文件中写入数据信息,有标签的话存放在数据最后位
:param csv_file_name: CSV文件名
:return: None,文件夹中会显示写入的数据信息
"""
import csv
with open(csv_file_name,"w",newline='') as csvfile:
writer = csv.writer(csvfile)#写出来存在逗号
# 没有逗号的写入方式,但是在读取的时候需要更改并处理数据
# writer=csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
#写入多行用writerows,写入单行用writerow
writer.writerows(Data)
print("Write All!")
def Write_Data():
import os
import cv2
#第一层文件夹目录
filename="..\\imgout\\"
Data = []
for file_1 in os.listdir(filename):
#第二层文件夹目录,第一层文件夹下的下一层文件夹目录
# print(file_1)file_1为文件名
filename_1 = os.path.join(filename, file_1)
Data_tmp = []
# print(file_1)
for file_2 in os.listdir(filename_1):
#第三层文件夹,找到对应文件的地址
filename_2 = os.path.join(filename_1, file_2)
Data_tmp1=[]
# print(filename_2)
img = cv2.imread(filename_2,0)
w,h=img.shape[:2]
# data=np.reshape(img,[w*h])
for i in range(w):
for j in range(h):
Data_tmp1.append(img[i,j])
#添加标签
Data_tmp1.append(file_1)
Data_tmp.append(Data_tmp1)
Data=Data+Data_tmp
Write_csv(Data)
下面是TensorFlow的数据制作:https://blog.csdn.net/zx520113/article/details/84556489