gpt4 book ai didi

python - 什么是更快、更 Pythonic 的方式来读取 CSV 并从中制作数据框?

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:14 27 4
gpt4 key购买 nike

输入:一个包含 50,000 行的 CSV;每行包含 910 列值 0/1。
输出:运行我的 CNN 的数据框。

我编写了一个逐行读取 CSV 的代码。对于每一行,我将数据分成两部分,称为神经元(900 列)和标签(10 列)。由于这些是列表,我将它们转换为 Numpy 数组。当我转到下一行时,我做同样的事情并将数组堆叠起来最终得到 4 个常规数据集:
x_train、x_test、y_train、y_test

我的代码可以正常工作,因为我在只有 6 行的小型 CSV 上对其进行了测试。但是当我在 50,000 行的实际数据集上运行它时,在数组初始化之后,将行转换为数据框需要很长时间。

所以我想知道是否有更快的方法来进行此转换,还是可以在这里等待!

这是我的代码:

import numpy as np
import pandas as pd
import time
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
from sklearn.model_selection import train_test_split

# Read the dataset from the CSV file into a dataframe
df = pd.read_csv("bci_dataset_labelled.csv")

start_init = time.time()

xvalues = np.zeros((900,), dtype=np.int)
yvalues = np.zeros((10,), dtype=np.int)

print("--- Arrays initialized in %s seconds ---" % (time.time() - start_init))

start_conversion = time.time()

for row in df.itertuples(index=False):
# separate the neurons from the labels
x = list(row[:900])
y = list(row[900:])

# convert the lists to numpy arrays
x = np.array(x)
y = np.array(y)

xvalues = np.vstack((xvalues, x))
yvalues = np.vstack((yvalues, y))

print("--- CSV rows converted to dataframe in %s seconds ---" % (time.time() - start_conversion))

start_split = time.time()

x_train, x_test, y_train, y_test = train_test_split(xvalues, yvalues, test_size=0.2)

print("--- Dataframe split into training and testing datasets in %s seconds ---" % (time.time() - start_split))

num_classes = y_test.shape[1]
num_neurons = x_train[0].shape[0]

# define baseline model
def baseline_model():
#create model
model = Sequential()
model.add(Dense(
num_neurons,
input_dim = num_neurons,
kernel_initializer = 'normal',
activation = 'relu'
))
model.add(Dense(
num_classes,
kernel_initializer = 'normal',
activation = 'softmax'
))
#compile model
model.compile(
loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = ['accuracy'])
return model

# build the model
model = baseline_model()

# fit the model
model.fit(x_train, y_train, validation_data = (x_test, y_test),
epochs = 10, batch_size = 200, verbose = 2)

# final evaluation of the model
scores = model.evaluate(x_test, y_test, verbose=0)
print("Baseline error: %0.2f%%" % (100-scores[1]*100))

它只是卡在这里:

Rachayitas-MacBook-Pro:bci_hp rachayitagiri$ python3 binarycnn.py 
Using TensorFlow backend.
--- Arrays initialized in 2.4080276489257812e-05 seconds ---

任何建议将不胜感激!谢谢!

编辑:将输出作为控制台的文本,而不是图片。谢谢你的建议。

最佳答案

你可能无法击败read_csv ,开箱即用,可能比现有的任何其他解决方案都经过更好的测试。

关于python - 什么是更快、更 Pythonic 的方式来读取 CSV 并从中制作数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com