数据集
下载&查看
Pima Indians Diabetes Data Set(皮马印第安人糖尿病数据集)
shape=(768,9)
该数据集总共九列(特征):
- Number of times pregnant 怀孕次数
- Plasma glucose concentration a 2 hours in an oral glucose tolerance test 葡萄糖
- Diastolic blood pressure (mm Hg) 血压
- Triceps skin fold thickness (mm) 皮层厚度
- 2-Hour serum insulin (mu U/ml) 胰岛素 2小时血清胰岛素
- Body mass index (weight in kg/(height in m)^2) 体重指数 (体重/身高)
- Diabetes pedigree function 糖尿病谱系功能
- Age (years) 年龄 (岁)
- Class variable (0 or 1) 类标变量 (0或1)是否患病
训练模型
import tensorflow as tf
import numpy
dataset=numpy.loadtxt('pima-indians-diabetes.csv',delimiter=',')
X=dataset[:,0:8]
Y=dataset[:,8]
#1 define the network
model=tf.keras.Sequential()
model.add(tf.keras.layers.Dense(12,input_dim=8,activation='relu'))
model.add(tf.keras.layers.Dense(1,activation='sigmoid'))
# 2 compile the network
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
#3 fitthe network
history=model.fit(X,Y,epochs=100,batch_size=10,verbose=1)
最后三个epoch,epoch增多,精度呈现上升趋势上升。
Epoch 98/100
768/768 [==============================] - 0s 130us/sample - loss: 0.5204 - accuracy: 0.7591
Epoch 99/100
768/768 [==============================] - 0s 126us/sample - loss: 0.5480 - accuracy: 0.7344
Epoch 100/100
768/768 [==============================] - 0s 122us/sample - loss: 0.5669 - accuracy: 0.7083
评估和预测模型
# 4 evaluate the network
loss,accuracy=model.evaluate(X,Y,verbose=1)
print('\nLoss: %.2f, Accuracy: %.2f'%(loss,accuracy*100))
# make predictions
probabilities=model.predict(X)
predictions=[float(numpy.round(x)) for x in probabilities]
acc=numpy.mean(predictions==Y)
print('Prediction Accuracy: %.2f%%'%(acc*100))
768/1 [=====] - 0s 109us/sample - loss: 0.5756 - accuracy: 0.7552
Loss: 0.51, Accuracy: 75.52
Prediction Accuracy: 75.52%
保存模型和权重
- 4.6 保存和加载模型 TensorFlow有两种保存模型的方法,一种是只保存模型的权重和偏置,另一种是保存整个模型。基本用法如
model.save_weights('./save_weights/my_save_weigthts')
model.load_weights('./save_weights/my_save_weigthts')
<tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x7f265c603850>
model.save('my_model.h5')
restored_model=tf.keras.models.load_model('./my_model.h5')