Во-первых, я последовал примеру, закодированному в Tutorials
и сделал следующие коды:
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
dataframe = pd.read_csv(URL)
dataframe.head()
train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
dataframe = dataframe.copy()
labels = dataframe.pop('target')
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
if shuffle:
ds = ds.shuffle(buffer_size=len(dataframe))
ds = ds.batch(batch_size)
return ds
batch_size = 32
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)
feature_columns = []
age = feature_column.numeric_column("age")
# numeric cols
for header in ['age', 'trestbps', 'chol', 'thalach', 'oldpeak', 'slope', 'ca']:
feature_columns.append(feature_column.numeric_column(header))
# bucketized cols
age_buckets = feature_column.bucketized_column(age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])
feature_columns.append(age_buckets)
# indicator cols
thal = feature_column.categorical_column_with_vocabulary_list(
'thal', ['fixed', 'normal', 'reversible'])
thal_one_hot = feature_column.indicator_column(thal)
feature_columns.append(thal_one_hot)
# embedding cols
thal_embedding = feature_column.embedding_column(thal, dimension=8)
feature_columns.append(thal_embedding)
# crossed cols
crossed_feature = feature_column.crossed_column([age_buckets, thal], hash_bucket_size=1000)
crossed_feature = feature_column.indicator_column(crossed_feature)
feature_columns.append(crossed_feature)
feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
model = tf.keras.Sequential([
feature_layer,
layers.Dense(128, activation='relu'),
layers.Dense(128, activation='relu'),
layers.Dense(1)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_ds,
validation_data=val_ds,
epochs=5)
loss, accuracy = model.evaluate(test_ds)
print("Accuracy", accuracy)
# Try to use predict to get the same accuracy
predictions = model.predict(test_ds)
for i, p in enumerate(predictions):
print(p, test.iloc[i,-1])
После выполнения я получил точность = 0,6885246.
Затем я пытаюсь использовать метод predict
для получения прогнозов оцененного набора данных, но результат, который я получил в print(p, test.iloc[i,-1]
:
[-1.7059733] 0
[-0.914219] 0
[2.6422875] 1
[-0.50430596] 1
[-1.2348572] 0
[-0.57301724] 0
[-2.1014583] 0
[-4.370711] 0
[0.21761642] 0
[-2.8065221] 0
[-3.2469923] 0
[-0.25715744] 1
[0.05394493] 1
[1.2391514] 0
[-3.7102253] 1
[-4.0611124] 0
[1.36385] 0
[-1.1096503] 0
[3.4140522] 1
[0.6951326] 0
[-3.232728] 0
[0.98346126] 0
[0.04960524] 0
[-0.90004027] 0
[1.918218] 0
[-0.02936329] 0
[-0.55671084] 1
[-2.1650188] 1
[-4.8975983] 0
[-1.5514184] 1
[-2.1743653] 0
[0.56928] 0
[-2.8607953] 0
[2.4095147] 0
[0.5155109] 1
[0.7517127] 0
[-1.6738821] 0
[-3.733505] 0
[2.2426589] 1
[-2.6165645] 0
[-2.1079547] 0
[-1.8746301] 0
[-4.116344] 0
[0.33854234] 1
[-2.3230617] 0
[-0.02075209] 1
[-0.33064234] 0
[1.6755556] 1
[1.1898655] 1
[0.40846193] 0
[-0.33131325] 0
[-0.63726294] 0
[-2.7144134] 0
[-0.48318636] 0
[1.516653] 1
[2.5299337] 1
[-2.1182806] 0
[-2.5583768] 1
[-0.65298045] 1
[-1.4936553] 0
[-0.7257029] 0
Мой вопрос: какой метод я следует использовать для преобразования результата с плавающей запятой в двоичный (0 или 1) и сравнить цель? Моя конечная цель - получить значение точности 0,6885246, полученное методом оценки.
Редактировать после полученного решения:
- изменить на "from_logits = false"
- изменить вывод layer "layer.Dense (1, активации = 'sigmoid')" *
- добавить следующие коды после model.predict
final_preds = [1 if x>0.5 else 0 for x in predictions]
m = 0
for i, p in enumerate(final_preds):
if p == test.iloc[i, -1]
m += 1
print(m / len(final_preds))
После запуска я получил:
Accuracy 0.6885246
0.6885245901639344