首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
社区首页 >问答
筛选
回答情况:
全部无回答回答未采纳
提问时间:
不限一周内一月内三月内一年内
回答标签:
tensorflow

TensorFlow有哪些应用实践?

壹捌柒肆
使用 TensorFlow 做机器学习 数据集描述 先描述下这里做实验的数据集,下载地址census income mld,是收集美帝的收入的记录,feature是一些个人信息包括工作、年纪、学历水平、家庭情况等等大概40个维度,标签是是否年收入在50k以上,即一个二类分类器。后面所有算法都是使用的相同的数据来做实验。 数据读入 数据集格式为csv,使用pandas可以快速读入数据,并格式化为DataFrame,做一些基本的预处理操作,如下,是从csv文件中读入数据的操作,因为Pandas内部会自动判断类型为object类型(categorical 值为02,40这类数字的值),在使用之前需要做转换,转为str类型,: TRAIN_FILE = '../data/census/census-income.data' TEST_FILE = '../data/census/census-income.test' df_train = pd.read_csv(TRAIN_FILE, names=COLUMNS, skipinitialspace=True) df_test = pd.read_csv(TEST_FILE, names=COLUMNS, skipinitialspace=True) df_train = df_train.dropna(how='any', axis=0) df_test = df_test.dropna(how='any', axis=0) df_train[[ 'detailed_industry_recode', 'detailed_occupation_recode', 'year', 'own_business_or_self_employed', 'veterans_benefits' ]] = df_train[[ 'detailed_industry_recode', 'detailed_occupation_recode', 'year', 'own_business_or_self_employed', 'veterans_benefits' ]].astype(str) df_test[[ 'detailed_industry_recode', 'detailed_occupation_recode', 'year', 'own_business_or_self_employed', 'veterans_benefits' ]] = df_test[[ 'detailed_industry_recode', 'detailed_occupation_recode', 'year', 'own_business_or_self_employed', 'veterans_benefits' ]].astype(str) df_train[LABEL_COLUMN] = ( df_train[LABEL_COLUMN].apply(lambda x: '+' in x)).astype(int) df_test[LABEL_COLUMN] = ( df_test[LABEL_COLUMN].apply(lambda x: '+' in x)).astype(int) dtypess = df_train.dtypes 从硬盘读入数据之后,如何标记每个维度的属性比如continous var还是categorical var,这个在sklearn上是很方便使用preprocessing.OneHotEncoder()可以很方便的处理,TF.learn内部也有类似的逻辑,相对会比较复杂: class_of_worker = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='class_of_worker', hash_bucket_size=1000) detailed_industry_recode = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='detailed_industry_recode', hash_bucket_size=1000) detailed_occupation_recode = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='detailed_occupation_recode', hash_bucket_size=1000) education = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='education', hash_bucket_size=1000) enroll_in_edu_inst_last_wk = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='enroll_in_edu_inst_last_wk', hash_bucket_size=1000) marital_stat = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='marital_stat', hash_bucket_size=1000) major_industry_code = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='major_industry_code', hash_bucket_size=1000) major_occupation_code = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='major_occupation_code', hash_bucket_size=1000) race = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='race', hash_bucket_size=1000) hispanic_origin = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='hispanic_origin', hash_bucket_size=1000) sex = tf.contrib.layers.sparse_column_with_keys( column_name='sex', keys=['Female', 'Male']) member_of_labor_union = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='member_of_labor_union', hash_bucket_size=1000) reason_for_unemployment = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='reason_for_unemployment', hash_bucket_size=1000) full_or_part_time_employment_stat = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='full_or_part_time_employment_stat', hash_bucket_size=1000) tax_filer_stat = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='tax_filer_stat', hash_bucket_size=1000) region_of_previous_residence = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='region_of_previous_residence', hash_bucket_size=1000) state_of_previous_residence = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='state_of_previous_residence', hash_bucket_size=1000) detailed_household_and_family_stat = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='detailed_household_and_family_stat', hash_bucket_size=1000) detailed_household_summary_in_household = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='detailed_household_summary_in_household', hash_bucket_size=1000) migration_code_change_in_msa = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='migration_code_change_in_msa', hash_bucket_size=1000) migration_code_change_in_msa = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='migration_code_change_in_msa', hash_bucket_size=1000) migration_code_change_in_reg = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='migration_code_change_in_reg', hash_bucket_size=1000) migration_code_move_within_reg = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='migration_code_move_within_reg', hash_bucket_size=1000) live_in_this_house_1year_ago = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='live_in_this_house_1year_ago', hash_bucket_size=1000) migration_prev_res_in_sunbelt = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='migration_prev_res_in_sunbelt', hash_bucket_size=1000) family_members_under18 = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='family_members_under18', hash_bucket_size=1000) country_of_birth_father = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='country_of_birth_father', hash_bucket_size=1000) country_of_birth_mother = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='country_of_birth_mother', hash_bucket_size=1000) country_of_birth_self = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='country_of_birth_self', hash_bucket_size=1000) citizenship = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='citizenship', hash_bucket_size=1000) own_business_or_self_employed = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='own_business_or_self_employed', hash_bucket_size=1000) fill_inc_questionnaire_for_veteran_admin = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='fill_inc_questionnaire_for_veteran_admin', hash_bucket_size=1000) veterans_benefits = tf.contrib.layers.sparse_column_with_hash_bucket( column_name='veterans_benefits', hash_bucket_size=1000) year = tf.contrib.layers.sparse_column_with_keys( column_name='year', keys=['94', '95']) # Continuous base columns age = tf.contrib.layers.real_valued_column('age') age_buckets = tf.contrib.layers.bucketized_column( age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) wage_per_hour = tf.contrib.layers.real_valued_column('wage_per_hour') capital_gains = tf.contrib.layers.real_valued_column('capital_gains') capital_losses = tf.contrib.layers.real_valued_column('capital_losses') dividends_from_stocks = tf.contrib.layers.real_valued_column( 'dividends_from_stocks') instance_weight = tf.contrib.layers.real_valued_column('instance_weight') weeks_worked_in_year = tf.contrib.layers.real_valued_column( 'weeks_worked_in_year') num_persons_worked_for_employer = tf.contrib.layers.real_valued_column( 'num_persons_worked_for_employer') real_valued_column 主要做连续性的特征,对categorical var这里有两种处理方式:一种是sparse_column_with_keys;另一种是sparse_column_with_hash_bucket,把对应的categorical var转换为对应的数字index。 def input_fn(df): # Creates a dictionary mapping from each continuous feature column name (k) to # # the values of that column stored in a constant Tensor. continuous_cols = { k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS } # Creates a dictionary mapping from each categorical feature column name (k) # to the values of that column stored in a tf.SparseTensor. categorical_cols = { k: tf.SparseTensor( indices=[[i, 0] for i in range(df[k].size)], values=df[k].values, dense_shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS } # Merges the two dictionaries into one. feature_cols = dict(continuous_cols.items() + categorical_cols.items()) # Converts the label column into a constant Tensor. label = tf.constant(df[LABEL_COLUMN].values) # Returns the feature columns and the label. return feature_cols, label 在经过特征的处理之后,由于我们这里数据没有直接格式化分开成data、target,所以我们要做一个input_fn的处理,将输入处理,参考仓库源码,将连续性特征转换为列名和constant值的dict,categorical转化为特殊格式的SparseTensor格式。 模型训练 数据处理好之后,做模型训练就比较容易了,如下图,配置好对应的FEATURE_COLUMNS和要保存model的路径就好了 def train_input_fn(): return input_fn(df_train) def eval_input_fn(): return input_fn(df_test) model_dir = '../model_dir' model = tf.contrib.learn.LinearClassifier( feature_columns=FEATURE_COLUMNS, model_dir=model_dir) model.fit(input_fn=train_input_fn, steps=200) results = model.evaluate(input_fn=eval_input_fn, steps=1) for key in sorted(results): print("%s: %s" % (key, results[key])) 最终结果如下图: 📷 这里,我仅仅是使用TF.Learn的LinearClassifier做了一个小的demo,后面会有其他算法,之后会加上更多的小技巧,如何更方便的在TF.Learn中用好机器学习。具体代码见tensorflow-101/machinelearning_toolkit/scripts/linear_classifier.py Support Vector Machine 支持向量机使用方法差不多,基本上可以复用linear_classifier.py中的代码,这里有三个比较不同的地方: SVM需要有一个example_id的列需要指定,所以我们需要在input_fn中将其加上; SVM的调用底层有一个reshape的bug,我在玩svm的过程发现了,具体描述在这儿check-failed-ndims-dims-2-vs-1-when-i-build-a-svm-model,大概原因是对连续值特征比如个数是200,而值的shape是(200,)而非(200, 1),提了个issue Check failed: NDIMS == dims() (2 vs. 1) when I build a svm model,后面RandomForest也有类似的问题,等着后续修复,暂时的解决方法是原先的continuous_cols修改为:continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS}; 模型替代SVM: model_dir = ‘../svm_model_dir’ model = svm.SVM(example_id_column=’example_id’, feature_columns=FEATURE_COLUMNS, model_dir=model_dir) model.fit(input_fn=train_input_fn, steps=10) results = model.evaluate(input_fn=eval_input_fn, steps=1) for key in sorted(results): print(“%s: %s” % (key, results[key])) svm的代码见:tensorflow-101/machinelear ning_toolkit/scripts/tf-svm.py 一个重现 real column bug 的例子: github.com/burness/tens 最终100个step的结果: RandomForest 随机森林的模型和linearClassifier的使用接口也有点差异,模型定义和训练的地方改为: validation_metrics = { "accuracy": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_accuracy, prediction_key='probabilities' ), "precision": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_precision, prediction_key='probabilities' ), "recall": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_recall, prediction_key='probabilities' ) } hparams = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams( num_trees=10, max_nodes=1000, num_classes=2, num_features=len(CONTINUOUS_COLUMNS) + len(CATEGORICAL_COLUMNS)) classifier = random_forest.TensorForestEstimator(hparams, model_dir=model_dir, config=tf.contrib.learn.RunConfig(save_checkpoints_secs=60)) classifier.fit(input_fn=train_input_fn, steps=200) results = classifier.evaluate( input_fn=eval_input_fn, steps=1, metrics=validation_metrics) print results for key in sorted(results): print("%s: %s" % (key, results[key])) 而且由于在训练的时候,前面linearClassifier和SVM都是没有任何输出,不是很友好,查了TensorFlow的文档,可以在训练过程中输出相关信息,只需要加一行tf.logging.set_verbosity(tf.logging.Infohttp://tfg)就可输出训练过程中的loss信息: 📷 当然这里是很粗糙的,另外不知道怎么的RF的evaluate没有accuracy的输出,为了输出相关的信息,我这里定义了validation_metrics传递给evaluate即可,后面在wide and deep的实验中会详细描述,最终结果: 📷 RF的源码见:tensorflow-101/machinelearning_toolkit/scripts/tf-rf.py wide and deep wide and deep可以很方便的在TF.Learn中定义使用,比较复杂的是做feature的一些处理,如wide column一般对实数列做bucket处理,如age_buckets = tf.contrib.layers.bucketized_column(age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]),这里需要给定boundaries,将连续值离散化,这里不知道是否有不需要指定boundaries的api或者按比例自己计算的,这个我后续调研下,离散后之后,可直接为wide列,但是通常会做更多的cross column: tf.contrib.layers.crossed_column(columns=[age_buckets, class_of_worker], hash_bucket_size=1000) 这里为了代码的简单,我就只错了两个维度的cross_column,以以前的经验来说,通常在特征维度上cross column这种效果提升会比较明显,尤其是linearClassifier这种线性模型。 deep的列通常不需要对连续性特征做多少处理,主要对categorical var在离线化之后需要向量化,通常会使用one_hot_column和embedding_column,通常one_hot_column会对sex、year这类值很容易穷举的,可取值不多,而embedding_column会重新向量化categorical var,官方源码里面有对这部分进行说明tensorflow/contrib/layers/python/layers/feature_column.py具体里面的算法暂时还不太清楚,后面我会来细细研究下。 基本上feature的处理就是这样,然后就是模型了: validation_metrics = { "accuracy": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_accuracy, prediction_key="classes"), "precision": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_precision, prediction_key="classes"), "recall": tf.contrib.learn.MetricSpec( metric_fn=tf.contrib.metrics.streaming_recall, prediction_key="classes") } validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(input_fn=eval_input_fn, every_n_steps=10, metrics=validation_metrics, eval_steps=1) if FLAGS.classifier_mode == 'wide': model = tf.contrib.learn.LinearClassifier(model_dir=model_dir, feature_columns=wide_columns, config=tf.contrib.learn.RunConfig(save_checkpoints_secs=60)) elif FLAGS.classifier_mode == 'deep': model = tf.contrib.learn.DNNClassifier(model_dir=model_dir, feature_columns=deep_columns, hidden_units=[128, 64], config=tf.contrib.learn.RunConfig(save_checkpoints_secs=60)) else: model = tf.contrib.learn.DNNLinearCombinedClassifier( model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=[128, 64], fix_global_step_increment_bug=True, config=tf.contrib.learn.RunConfig(save_checkpoints_secs=60)) model.fit(input_fn=train_input_fn, steps=train_step, monitors=[validation_monitor]) results = model.evaluate(input_fn=eval_input_fn, steps=1) for key in results: print "%s: %s" % (key, results[key]) 这里我仿照了tutorial里面的写法,根据传参来定义不同模型,包括wide model、deep model 和 wide and deep model,在跑模型的过程中,配置log为INFO,只能打印loss,信息量太小, 这里使用validationMonitor,使用validationMonitor这里有个bug,必须要设置eval_steps=1才行,github 上有个issue专门提到过tf.contrib.learn.monitors.ValidationMonitor hangs when passed input_fn parameter,但是TensorFlow没有修复,原因是后续会使用Hooks来替代monitors,哎,动不动就重写,真是任性,这里为了使用validationMonitor,需要配置config才行,这里我每60s保存下ckpt,也可以用更多的策略来配置,也可以在validationMonitor中配置Early Stopping,使在对应的metrics变差时,及时停止训练: 📷 最后实验的效果: 📷 另外,某个dnn的input feature的embedding可视化界面: 📷

python代码报错KeyError:-1,请问如何解决?

冰书
`KeyError: -1` 是一个Python运行时错误,通常发生在尝试访问字典或列表中不存在的键或索引时。在这种情况下,代码试图访问键为 `-1` 的元素,但该键在字典或列表中不存在。 要解决这个问题,你可以采取以下几种方法: 1. **检查键或索引是否存在**:在访问字典或列表中的元素之前,确保键或索引存在。你可以使用 `if key in my_dict:` 或 `if -1< index < len(my_list):` 等条件语句来检查。 2. **使用 `get()` 方法**:对于字典,你可以使用 `get()` 方法来避免 `KeyError`。`get()` 方法允许你为不存在的键提供一个默认值。例如:`my_dict.get(key, default_value)`。 3. **使用 `try-except` 语句**:使用 `try-except` 语句捕获 `KeyError`,并在异常发生时执行相应的处理代码。例如: python try: value = my_dict[-1] except KeyError: value = "default_value" 4. **检查代码逻辑**:仔细检查代码逻辑,确保在访问字典或列表元素之前已经正确地初始化了字典或列表。 5. **使用 `collections.defaultdict`**:对于字典,你还可以使用 `collections.defaultdict` 类来创建一个具有默认值的字典。例如: python from collections import defaultdict my_dict = defaultdict(lambda: "default_value") value = my_dict[-1] # 如果 -1 不存在,将返回 "default_value" 根据具体情况,选择合适的方法来解决 `KeyError: -1` 问题。如果你需要更多帮助,请提供有关错误的上下文信息,以便我们能够更好地帮助你。

腾讯云是什么?

编辑2024-02-1390
用户11002471
腾讯云(Tencent Cloud)是由中国科技巨头腾讯(Tencent)推出的云计算服务平台。它提供了各种云计算基础设施、云服务和解决方案,包括但不限于计算、存储、网络、数据库、人工智能、大数据、物联网等领域。腾讯云致力于为个人开发者、中小企业和大型企业提供高性能、高可靠性、安全稳定的云计算服务。 腾讯云的服务范围涵盖了全球多个地区和国家,包括中国大陆、中国香港、东南亚、欧洲、北美等地区,为用户提供了便捷的部署和管理方式,以满足不同地区用户的需求。腾讯云通过提供强大的基础设施和丰富的云服务,帮助用户实现数字化转型、创新业务、提高运营效率,并为他们的业务提供可靠的技术支持。 腾讯云的产品和服务包括云服务器、对象存储、数据库、云网络、安全服务、人工智能、大数据分析等,覆盖了从基础的云计算服务到高级的人工智能和大数据解决方案的全方位需求。无论是个人开发者还是大型企业,都可以在腾讯云上找到适合自己业务需求的云计算解决方案。

使用tensorflow进行迭代过程出现failed to allocate memory的bug?

编辑2021-10-222.3K
用户9248186
解决了吗兄弟我也不会啊

Tensorflow访问 HDFS 出现问题?

编辑2021-10-031.9K
卖女孩的火柴
从 2.6.0 版本开始,您需要将 tensorflow_io 与 tensorflow 一起导入: 安装方式: pip install tensorflow-io import tensorflow as tf import tensorflow_io as tfio

请问python里有util. model_util模块吗?

云深无际
很明显没有

请问python里有util. model_util模块吗?

泰坦HW
这个并不是Python的官方库中的模块,应该是第三方开发者编写的包、工具模块。

您好,请问您是通过pip 安装的tensorflow ?

编辑2020-08-07214
无聊至极
可以前往作者专栏留言处提问喔

如何查看tione的sdk自定义镜像任务失败状态的日志?

腾讯云TI平台回答已采纳
针对您的第一个问题,请问您是否在训练代码里打印日志了? 针对您第二个问题,需要您提供下您的腾讯云账户ID,后台帮您查询下哦!

学校的腾讯云上实验室。实验1搭建的python、tensorflow环境怎么保存?

编辑2020-05-09253
mariolu
在docker环境搭建,搭建完后保存成镜像,然后以后就拷贝到(或者上传到你的镜像库)新环境运行安装

tensorflow实验应该购买什么配置的云平台?

用户6974342
我买了标准型S2,可以进行第一个实验,但是进行第二个实验的时候说不行:“当前实验室暂不支持使用自有云主机进行试验”

TensorFlow控制台-> App详情->stdot 日志界面太长后面的不更新了?

腾讯云TI平台
没有限制的哦

Tensorflow2.0卷积时报错?

编辑2019-12-063.6K
用户7066303
你必须要在import库的代码后面加上那几句话,别的地方加不行,这样就可以解决问题了

今天试用了一下TI?

腾讯云TI平台
您好,感谢试用。 关于第一个文件上传问题,上传成功的文档是会显示在左边文件栏的,您可以从这个判断是否有顺利上传。 关于第二个unzip问题,想问下您的文件是否有超过2G,超过的话是没法用unzip了。

训练神经网络中途被kill?

富有想象力的人
是否由于cpu或者内存等资源问题导致

CPU不支持的编译模式。是不是虚拟机环境的TF有问题?

编辑2019-11-04625
用户6227418
这个不是info么,我也有提示这句话,不过好像不影响运行。弱弱问一句,为啥结果不太一样?

用pycharm在运行tensorflow时候,出现W0716警告,怎么忽略或者说怎么消除?

用户5908279
老哥你的问题解决了吗?我也是打印这个警告消息,就是W+当前日期,用网上tensorflow屏蔽警告信息的方法不管用额。。。

请问一下tensorflow 是怎么调整参数的?

HuangWeiAI
是的,w和b这些变量由tf.Variable来表示,你可以通过如下方式打印查看这些变量 vars = tf.trainable_variables() print(vars ) #打印tf格式变量 vars_vals = sess.run(vars) for var, val in zip(vars, vars_vals): print("var: {}, value: {}".format(var.name, val)) #打印变量值

读入tfrecords文件时出现警告,程序一直运行不能停,print标记后发现未打印数据,如何修改?

用户6368026
哥们,你弄好了吗?怎么弄的?

tensorflow tf,argmax()函数怎么理解?

编辑2018-10-171.2K
Dingda
def argmax(self, axis=None, fill_value=None, out=None): 返回沿着某个维度最大值的位置 Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had the value fill_value. Parameters ---------- axis : {None, integer} If None, the index is into the flattened array, otherwise along the specified axis fill_value : {var}, optional Value used to fill in the masked values. If None, the output of maximum_fill_value(self._data) is used instead. out : {None, array}, optional Array into which the result can be placed. Its type is preserved and it must be of the right shape to hold the output. Returns
Hi~
今天想聊点什么呢?
近期活跃用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档