本案例使用Python的tensorflow、jupyternotebook、pandas进行训练学习
1.使用Pandas读取数据
import pandas as pd
import tensorflow as tf
df=pd.read_csv("./datas/heart/heart.csv")
df.head()
df.dtypes
#把thal列变成数字编码
df['thal']=pd.Categorical(df['thal'])
df['thal']=df['thal'].cat.codes
df.head()
2.将数据加载到tf.data.Dataset
#要预测的目标,这是一个二分类问题
target=df.pop('target')
df.head()
target.head()
df.head().values
df.shape
target.head().values
#构建dataset,其实是把pandas数据转换成numpy数组进行转换的
dataset=tf.data.Dataset.from_tensor_slices((df.values,target.values))
for features,label in dataset.take(5):
print('Features:{},Label:{}'.format(features,label))
#Shuffle and batch the dataset
train_dataset=dataset.shuffle(len(df)).batch(1)
3.创建并训练模型
model=tf.keras.Sequential([
tf.keras.layers.Dense(10,input_shape=(df.shape[1],)),
tf.keras.layers.Dense(10,activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model.summary()
model.fit(train_dataset,epochs=15)