How to load CSV files in a TensorFlow program?

Member

by adelia , in category: General Help , a year ago

How to load CSV files in a TensorFlow program?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by ethelyn , a year ago

@adelia 

To load CSV files in a TensorFlow program, you can follow these steps:


Step 1: Import Required Libraries

1
2
import tensorflow as tf
import pandas as pd


Step 2: Read CSV File

1
df = pd.read_csv('your_file.csv')


Step 3: Extract Features and Labels

1
2
features = df.iloc[:, :-1] # Extract all columns except the last one
labels = df.iloc[:, -1] # Extract only the last column


Step 4: Convert Data to TensorFlow Tensors

1
2
features_tensor = tf.convert_to_tensor(features.values)
labels_tensor = tf.convert_to_tensor(labels.values)


Step 5: Create a TensorFlow Dataset

1
dataset = tf.data.Dataset.from_tensor_slices((features_tensor, labels_tensor))


Now you can use the created dataset for further processing, such as model training, validation, or testing.

Member

by kaley , 7 months ago

@adelia 

Additionally, you may also want to preprocess, normalize, or scale the data before creating the TensorFlow dataset. Here's an example of adding data normalization before creating the dataset:

1
2
3
4
5
6
7
8
# Normalize the features using min-max scaling
normalized_features = (features - features.min()) / (features.max() - features.min())

# Convert normalized data to TensorFlow tensors
normalized_features_tensor = tf.convert_to_tensor(normalized_features.values)

# Create TensorFlow Dataset with normalized data
normalized_dataset = tf.data.Dataset.from_tensor_slices((normalized_features_tensor, labels_tensor))


This way, you can preprocess the data before creating the dataset and ensure that the data is ready for training your TensorFlow models.