线性回归
详情见link.
多层感知器(神经网络)
import tensorflow as tfimport pandas as pd# 提取数据data = pd.read_csv(\'/..../tfb.csv\')x = data.iloc[:,0:-1]y = data.iloc[:,-1]#建立顺序模型#Dense(输出,输入,激励函数)model = tf.keras.Sequential([tf.keras.layers.Dense(10, input_shape=(3,), activation = \'relu\'),tf.keras.layers.Dense(1)])#model.summary 显示模型结构#配置优化器,损失函数model.compile(optimizer=\'adam\'loss=\'mse\')#自定义学习效率#model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01))#训练模型model.fit(x,y,epochs=100)#预测test = data.iloc[:10,1:-1]model.predict(test)
逻辑回归
import tensorflow as tfimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt#数据提取data = pd.read_csv(\'/..../tfb.csv\')x = data.iloc[:,:-1]y = data.iloc[:,-1].replace(-1,0)#-1替换为0#建立顺序模型model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(4,input_shape=(15,),activation=\'relu\'))model.add(tf.keras.layers.Dense(4,activation=\'relu\'))model.add(tf.keras.layers.Dense(1,activation=\'sigmold\'))#配置优化器,损失函数model.compile(optimizer=\'adam\'loss=\'binary_crossentropy\',metrics =[\'acc\'])# 训练模型history = model.fit(x,y,epochs=100)#loss以及acc图形绘制plt.plot(history.epoch,history.history[\'loss\'])plt.plot(history.epoch,history.history[\'acc\'])plt.show()
softmax分类
import tensorflow as tfimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt(train_image,train_lable),(test_image,test_label)=tf.keras.datasets.fashion_mnist.load_data()#train_image.shape 显示数据形状#plt.imshow(train_image[0]) #显示第一张图片#数据归一化train_image = train_image/255test_image = test_image/255#建立模型model = tf.keras.Sequential()model.add(tf.keras.layers.Flatten(input_shape=(28,28)))#降维model.add(tf.keras.layers.Dense(128,activation=\'relu\'))model.add(tf.keras.layers.Dropout(0.5))#使用Dropout防止过拟合model.add(tf.keras.layers.Dense(10,activation=\'softmax\'))#配置优化器,损失函数model.compile(optimizer=\'adam\',loss=\'sparse_categorical_crossentropy\',metrics=[\'acc\'])#顺序编码转变独热编码#train_lable_onehot = tf.keras.utils.to_catagorical(train_label)#test_lable_onehot = tf.keras.utils.to_catagorical(test_label)#model.compile(optimizer=\'adam\',loss=\'categorical_crossentropy\',metrics=[\'acc\'])#训练模型model.fit(train_image,train_lable,epochs=5)#添加训练中的acc和loss值#model.fit(train_image,train_lable,epochs=5,validation_data=(test_image,test_lable))#评价模型model.evaluate(test_image,test_label)#预测predict = model.predict(test_image)#具体到某一个np.argmax(predict[0])#预测标签test_image[0]#实际标签