import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib as plt
from sklearn.model_selection import train_test_split
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.preprocessing import StandardScaler
import functools
LABEL_COLUMN = 'Endstage'
LABELS = [1, 2, 3, 4]
x = pd.read_csv('HCVnew.csv', index_col=False)
def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=35, # Artificially small to make examples easier to show.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
return dataset
SELECT_COLUMNS = ["Alter", "Gender", "BMI", "Fever", "Nausea", "Fatigue",
"WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
"RNABase", "RNA4", "Baseline", "Endstage"]
DEFAULTS = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
temp_dataset = get_dataset("HCVnew.csv",
select_columns=SELECT_COLUMNS,
column_defaults=DEFAULTS)
def pack(features, label):
return tf.stack(list(features.values()), axis=-1), label
packed_dataset = temp_dataset.map(pack)
"""
for features, labels in packed_dataset.take(1):
print(features.numpy())
print()
print(labels.numpy())
"""
NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
"WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
"RNABase", "RNA4", "Baseline", "Endstage"]
desc = pd.read_csv("HCVnew.csv")[NUMERIC_FEATURES].describe()
MEAN = np.array(desc.T['mean'])
STD = np.array(desc.T['std'])
def normalize_numeric_data(data, mean, std):
# Center the data
return (data-mean)/std
# See what you just created.
raw_train_data = get_dataset("HCVnew.csv")
raw_test_data = get_dataset("HCVnew.csv")
class PackNumericFeatures(object):
def __init__(self, names):
self.names = names
def __call__(self, features, labels):
numeric_freatures = [features.pop(name) for name in self.names]
numeric_features = [tf.cast(feat, tf.float32) for feat in numeric_freatures]
numeric_features = tf.stack(numeric_features, axis=-1)
features['numeric'] = numeric_features
return features, labels
NUMERIC_FEATURES = ["Alter", "Gender","BMI", "Fever", "Nausea", "Fatigue",
"WBC", "RBC", "HGB", "Plat", "AST1", "ALT1", "ALT4", "ALT12", "ALT24", "ALT36", "ALT48", "ALT24w",
"RNABase", "RNA4", "Baseline", "Endstage"]
packed_train_data = raw_train_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
packed_test_data = raw_test_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
normalizer = functools.partial(normalize_numeric_data, mean=MEAN, std=STD)
numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
numeric_columns = [numeric_column]
numeric_layer = tf.keras.layers.DenseFeatures(numeric_columns)
preprocessing_layer = tf.keras.layers.DenseFeatures(numeric_columns)
#———————————————————————MODEL———————————————————————————————————————————————————————————————————————————————————————————
model = tf.keras.Sequential([
preprocessing_layer,
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
data_x = get_dataset("HCVnew.csv")
train_data = data_x.shuffle(500)
model.fit(train_data, epochs=20)
Здравствуйте, я пытаюсь создать нейронную сеть, которая может прогнозировать гепатит C на основе файла CSV, содержащего информацию о пациенте, и я не могу исправить ошибку ... Я получаю сообщение об ошибке: KeyError 'Endstage', тогда как Endstage - это столбец csv, который содержит соответствующие значения (от 1 до 4) и служит столбцом метки. Если у кого-то есть идея, которая может решить мою проблему, пожалуйста, скажите мне. Большое спасибо за вашу помощь!