TensorFlow2.0使用DenseFeature作为Functional API第一层时所遇到的问题

在尝试使用TensorFlow2.0的Keras Functional API构建网络时,作者遇到了'DenseFeatures'对象没有'shape'属性的错误。通过在GitHub上寻找解决方案,发现需要将原始特征列赋值为tf.keras.Input。修改代码后,问题得到解决。分享这个问题和解决方案,以帮助其他开发者避免相同困扰。
摘要由CSDN通过智能技术生成

本人小白,这几天在学习TensorFlow2.0,想使用Keras的Functional API来搭建一个简单的网络。

起初是按照网上的“心脏病预测实例”一步一步的操作,ok,没什么大问题。但我打算把model的表达方式用Functional API的方式来实现时却报错AttributeError: ‘DenseFeatures’ object has no attribute ‘shape’。

下面是我的代码,其余部分就不贴出来了,和例子一样。

# 以下为我自己改写的代码
feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
dense1 = tf.keras.layers.Dense(128, activation='relu')(feature_layer)
dense2 = tf.keras.layers.Dense(128, activation='relu')(dense1)
dense3 = tf.keras.layers.Dense(1, activation='sigmoid')(dense2)
model = tf.keras.Model(inputs=feature_layer, outputs=dense3)

# 以下为例子中的代码
# model = tf.keras.Sequential([
#     tf.keras.layers.DenseFeatures(feature_columns),
#     tf.keras.layers.Dense(128, activation='relu'),
#     tf.keras.layers.Dense(128, activation='relu'),
#     tf.keras.layers.Dense(1, activation='sigmoid')
# ])

当时卡了好久,最终在GitHub上找到了解决办法,在这里分享给大家,希望大家不要再遇到这个坑了。

解决方法:As unfortunate as this is, for now you will have to make it work by assigning tf.keras.Input to each original feature column that you have, i.e., those numeric feature column and categorical feature columns.

好吧,试着改了一下我的代码,果然能跑通了,呜呜呜呜呜呜呜卡了半个多月的问题终于解决了!!!

下面是使用Functional API + DenseFeature实现代码:

from __future__ import absolute_import, division, print_function

import numpy as np
import pandas as pd

# !pip install tensorflow==2.0.0-alpha0
import tensorflow as tf

from tensorflow import feature_column
from tensorflow import keras
from
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值