Tensorflow读取CSV数据

时间:2019-01-17 15:37:53

标签: python csv tensorflow

如何在tensorflow中读取CSV文件以手动替换training_x和training_y中的数据,我的Python代码是:

import tensorflow as tf 
from tensorflow import keras
import os
import pandas


model = keras.Sequential()

input_layer = keras.layers.Dense(3, input_shape=[3], activation='tanh')
model.add(input_layer)
output_layer = keras.layers.Dense(1, activation='sigmoid')
model.add(output_layer)
gd = tf.train.GradientDescentOptimizer(0.01)
model.compile(optimizer=gd, loss='mse')

dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path + "dados.csv"

......

training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])

training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

CSV文件:

outlook,humidity,wind,play
1,1,0,0

1 个答案:

答案 0 :(得分:0)

我找到了解决方法

file = ("dados.csv")

def data_encode(file):
    X = []
    Y = []
    train_file = open(file, 'r')
    for line in train_file.read().strip().split('\n'):
        line = line.split(',')
        X.append([int(line[0]), int(line[1]), int(line[2])])
        Y.append(int(line[3]))
    return X, Y

train_X , train_Y = data_encode(file)