导包并设置tensorflow GPU 这一步非常重要,否则后面模型训练model.fit()会报错
数据集在最后。
import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
gpus=tf.config.list_physical_devices('GPU')
if gpus:
gpu0=gpus[0]
tf.config.experimental.set_memory_growth(gpu0,True)
tf.config.set_visible_devices([gpu0],'GPU')
加载数据集
df=pd.read_csv('heart.csv')
print(df.head(5))
print(df.info)
print(df.isnull().sum())
x=df.iloc[:,:-1]
y=df.iloc[:,-1]
x_train,x_test,y_train,y_test =train_test_split(x,y,test_size=0.1,random_state=1)
方法介绍:df.loc与df.iloc前者传入的是标签名,后者只需要传入便签的索引。比如:
df.loc[:,'target']与df.iloc[:,-1]是一样的。
利用sklearn实现数据标准化:主要是去均值与方差
#%%标准化 每一列标准化
sc=StandardScaler()
x_train=sc.fit_transform(x_train)
x_test=sc.transform(x_test)
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],1)
x_test=x_test.reshape(x_test.shape[0],x_test.shape[1],1)
其中,fit_transform()方法计算了均值与方差,后面的transform方法是使用了前者的均值与方程差,因为他们都是在同一个数据集中划分的,而前者数据量多,计算方差均值准确。
创建模型
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LSTM,SimpleRNN
model=Sequential()
model.add(SimpleRNN(200,input_shape=(13,1),activation='relu'))
model.add(Dense(100,activation='relu'))
model.add(Dense(1,activation='relu'))
model.summary()
SimpleRNN(200,input_shape=(13,1),activation='relu')创建输入是(13,1)输出是200维,激活函数是relu的RNN
模型训练
opt=tf.keras.optimizers.Adam(learning_rate=1e-4)
model.compile(loss='binary_crossentropy',optimizer=opt,metrics='accuracy')
epochs=100
history=model.fit(x_train,y_train,epochs=epochs,batch_size=4,validation_data=(x_test,y_test), verbose=1)
模型评估
#%%模型评估
import matplotlib.pyplot as plt
acc=history.history['accuracy']
val_acc=history.history['val_accuracy']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs_range=range(epochs)
plt.figure(figsize=(14,4))
plt.subplot(1,2,1)
plt.plot(epochs_range,acc,label='training accuracy')
plt.plot(epochs_range,val_acc,label='validation accuracy')
plt.title('training and validation accuracy')
plt.subplot(1,2,2)
plt.plot(epochs_range,loss,label='training loss')
plt.plot(epochs_range,val_loss,label='validation loss')
plt.title('training and validation loss')
plt.show()
#%%
scores=model.evaluate(x_test,y_test,verbose=0)
print('%s:%.2f%%'%(model.metrics_names[1],scores[1]*100))
深度学习想带练,也想每周都能学习NLP或CV的话,可以联系我。
数据集:https://pan.baidu.com/s/1fB_KqsejBcWVMyjMQxd3Qg?pwd=i7pa