参考:https://blog.csdn.net/weixin_39445556/article/details/83930186
数据导入和X的处理与线性回归一致
# ---------------------逻辑回归---------------------
# 与线性回归对比,X轴一样,Y轴需要根据阈值转换数据
# 阈值设置
K = 200
# 创建一个和Y一样结构的矩阵
NY = np.zeros([L,1])
YY = np.array(CsvFile['PM25']).reshape([L,1])
# 将矩阵中大于阈值的等于1,小于等于阈值的等于0
for i in range(len(YY)):
if YY[i,0]>K:
NY[i,] = 1
else:
NY[i,] = 0
# 把全部数据切分成训练和验证两部分数据,X0,NY0是训练数据,X1,NY1是验证数据
X0,X1,NY0,NY1 = train_test_split(X,NY,test_size = 0.5,random_state = 0)
# 按TensorFlow做分类数据转换,转换为one-hot型因变量,由X1=分类1,X2=分类2转换为x1=[1,0],x2=[0,1]
NY0=to_categorical(NY0)
NY1=to_categorical(NY1)
print(NY0.shape)
# 定义模型输入
inp1 = Input([M,N,3])
# 定义输出,因为是二分类Dense设置为2
outp1 = Dense(2)(Flatten()(inp1))
# 激活,Dense是线性组合转换为概率
outp1 = Activation('softmax')(outp1)
NewModel = Model(inp1,outp1)
NewModel.summary()
3686400分类数,加截距项分类数=7,372,802
模型配置
# 定义模型的:loss:损失函数为categorical_crossentropy,optimizer:优化器,metrics:验证方式
NewModel.compile(optimizer = Adam(0.01),loss = 'categorical_crossentropy',metrics = ['accuracy'])
# 建立模型X0,NY0为训练集,验证集为X1,NY1,每个batch包含100样本,迭代次数为10次
NewModel.fit(X0,NY0,validation_data=(X1,NY1),batch_size=100,epochs=10)
# 找张图验证下模型,图片处理方式和之前X的处理方式一致,只不过这次是只有一张图片
pic2 = Image.open('./data/201612230930.jpg')
pic2 = pic2.resize([N,M])
pic2 = np.array(pic2).reshape([1,M,N,3])
pic2 = pic2/255
# 将二分类返回的矩阵转换成布尔型
n = np.array(NewModel.predict(pic2),dtype = bool)
m = np.array(['轻度污染','严重污染'])
# 第一类为轻度污染,第二类为严重污染,用布尔的矩阵作为索引取结果
print(m[n[0]])
plt.imshow(pic2[0])
# 查看模型数据结构
NewModel.layers
[<keras.engine.input_layer.InputLayer at 0x24dfee68f10>,
<keras.layers.core.flatten.Flatten at 0x24d49c750d0>,
<keras.layers.core.dense.Dense at 0x24dfee68eb0>,
<keras.layers.core.activation.Activation at 0x24dfee68f70>]
假设我们想看dense这一层下标应该是2
NewModel.layers[2].get_weights()
NewModel.layers[2].get_weights()[0].shape
(3686400, 2)
NewModel.layers[2].get_weights()[1].shape
(2,)为截距项