首页 \ 问答 \ 为什么这个Tensorflow程序工作?(Why does this Tensorflow program work?)

为什么这个Tensorflow程序工作?(Why does this Tensorflow program work?)

我在Mac OS 10.12.4,Anaconda Python 3.5和Tensorflow 1.1上运行。 我拼凑了下面显示的可重复代码。 我用参数“features”和“labels”定义了“my_model”。 我没有定义它们。 不带任何参数调用“my_model”函数。 程序运行后,我的Spyder“变量”窗口不显示它们。 我的问题是:这些变量在哪里定义?

查尔斯

from sklearn import metrics, cross_validation
from tensorflow.contrib import layers
from tensorflow.contrib import learn
from sklearn.preprocessing import LabelEncoder
import pandas as pd

# shut up the warnings
import warnings
warnings.filterwarnings('ignore')
import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)

def my_model(features, labels):
    labels = tf.one_hot(labels, 3, 1, 0)
    features = layers.stack(features, layers.fully_connected, [10, 20, 10])
    prediction, loss = (learn.models.logistic_regression(features, labels))
    train_op = tf.contrib.layers.optimize_loss(
        loss,
        tf.contrib.framework.get_global_step(),
        optimizer='Adagrad',
        learning_rate=0.1)

    return {'class': tf.argmax(prediction, 1), 'prob': prediction}, loss, train_op

df = pd.read_csv("iris.csv")
df = df.sample(frac=1)  # shuffle all rows
print(df.head())
column_names = list(df.columns[:4])
X = df[column_names].as_matrix()
y = df['Species']
le = LabelEncoder()
le.fit(df["Species"])
y = le.transform(df["Species"])
x_train, x_test, y_train, y_test = cross_validation.train_test_split(
  X, y, test_size=0.2, random_state=35)

classifier = tf.contrib.learn.Estimator(model_fn = my_model)
classifier.fit(x_train, y_train, steps=1000)

y_predicted = [p['class'] for p in classifier.predict(x_test, as_iterable=True)]
score = metrics.accuracy_score(y_test, y_predicted)
print('Accuracy: {0:f}'.format(score))

I'm running on Mac OS 10.12.4, Anaconda Python 3.5 and Tensorflow 1.1. I have cobbled together the reproducible code shown below. I have defined "my_model" with arguments "features" and "labels". I did not define them. The "my_model" function is called without any arguments. My Spyder "variables" window does not show them after the program runs. My question is: where are these variables defined?

Charles

from sklearn import metrics, cross_validation
from tensorflow.contrib import layers
from tensorflow.contrib import learn
from sklearn.preprocessing import LabelEncoder
import pandas as pd

# shut up the warnings
import warnings
warnings.filterwarnings('ignore')
import logging
logging.getLogger("tensorflow").setLevel(logging.ERROR)
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)

def my_model(features, labels):
    labels = tf.one_hot(labels, 3, 1, 0)
    features = layers.stack(features, layers.fully_connected, [10, 20, 10])
    prediction, loss = (learn.models.logistic_regression(features, labels))
    train_op = tf.contrib.layers.optimize_loss(
        loss,
        tf.contrib.framework.get_global_step(),
        optimizer='Adagrad',
        learning_rate=0.1)

    return {'class': tf.argmax(prediction, 1), 'prob': prediction}, loss, train_op

df = pd.read_csv("iris.csv")
df = df.sample(frac=1)  # shuffle all rows
print(df.head())
column_names = list(df.columns[:4])
X = df[column_names].as_matrix()
y = df['Species']
le = LabelEncoder()
le.fit(df["Species"])
y = le.transform(df["Species"])
x_train, x_test, y_train, y_test = cross_validation.train_test_split(
  X, y, test_size=0.2, random_state=35)

classifier = tf.contrib.learn.Estimator(model_fn = my_model)
classifier.fit(x_train, y_train, steps=1000)

y_predicted = [p['class'] for p in classifier.predict(x_test, as_iterable=True)]
score = metrics.accuracy_score(y_test, y_predicted)
print('Accuracy: {0:f}'.format(score))

原文:https://stackoverflow.com/questions/43746095
更新时间:2023-09-13 16:09

最满意答案

在文件less.h是你的答案:

#define public      /* PUBLIC FUNCTION */

看起来公众只是作为公共/全局功能和变量的标记。 编译后,它被扩展为无。

如何找到这些信息?

  1. 从顶部搜索.c文件到您想了解更多信息的标识符的位置
  2. 如果您没有找到任何声明,请查找#include指令
  3. 打开任何包含的文件并查找您要查找的声明
  4. 对于每个包含文件,从第二步开始重复

在这种情况下,这很简单。


In the file less.h is your answer:

#define public      /* PUBLIC FUNCTION */

It seems like public is only used as a marker for public/global functions and variables. When compiled, it is expanded to nothing.

How to find this information?

  1. Search the .c file from top to the location of the identifier you want more information about
  2. If you do not find any declaration, look for #include directives
  3. Open any included file and look for the declaration of what you are looking for
  4. Repeat from step two for every included file

In this case, that was pretty simple.

相关问答

更多
  • 变量应该始终具有可能的较小范围。 这背后的理由是,每当你增加范围时,你就会有更多的代码可能修改变量,因此解决方案会导致更多的复杂性。 因此很清楚,如果设计和实现自然允许,则避免使用全局变量是首选。 由于这个原因,我不喜欢使用全局变量,除非它们真的需要。 我无法同意“永不”的说法,就像任何其他概念一样,全局变量是在需要时应该使用的工具。 我宁愿使用全局变量,而不愿使用一些人为的构造(比如传递指针),这只会掩盖真正的意图。 使用全局变量的好例子是单例模式实现或嵌入式系统中的寄存器访问。 关于如何实际检测全局变量 ...
  • static关键字:在C ++中,static既可用于声明类级实体,也可用于声明特定于模块的类型。 在C#中,static仅用于声明类级实体。 适用于您的链接, C#开发人员的C# The static keyword: In C++, static can be used both to declare class-level entities and to declare types that are specific to a module. In C#, static is only used to ...
  • 在编译时,编译器将每个全局符号以强或弱方式导出到汇编器,并且汇编器将该信息隐式地编码到可重定位目标文件的符号表中。 函数和初始化的全局变量会得到强大的符号。 未初始化的全局变量得到弱符号。 考虑到强和弱符号的概念,Unix连接器使用以下规则处理多重定义的符号: 规则1:不允许使用多个强符号。 规则2:给定一个强符号和多个弱符号,选择强符号。 规则3:给定多个弱符号,选择任何弱符号。 您的代码A1.c如下所示: int i=0; // Strong Symbol void main() {} A2.c如下: ...
  • 变量k在技术上可用于其他文件(模块),但除非其他文件具有extern int k声明,否则它们将不知道该变量,并且编译时错误将指示k在另一个文件中是未知的。 The variable k will technically be available to other files (modules) but unless the other files have an extern int k declaration, they won't know about the variable and a compi ...
  • 在文件less.h是你的答案: #define public /* PUBLIC FUNCTION */ 看起来公众只是作为公共/全局功能和变量的标记。 编译后,它被扩展为无。 如何找到这些信息? 从顶部搜索.c文件到您想了解更多信息的标识符的位置 如果您没有找到任何声明,请查找#include指令 打开任何包含的文件并查找您要查找的声明 对于每个包含文件,从第二步开始重复 在这种情况下,这很简单。 In the file less.h is your answer: #define publi ...
  • 提高可读性的最佳方法是创建局部变量。 这个局部变量将在最终的可执行文件中得到优化,因此不会影响程序的性能。 局部变量可以是struct成员的硬拷贝,也可以是指向它的指针,具体取决于各种情况下最方便的内容。 您也可以通过各种方式使用宏,但我不推荐它,因为它们会使全局命名空间变得混乱。 如果您仍然坚持使用宏,无论出于何种原因,那么您应该这样做: #define SHORT var1.var2.var3.var4.myGlobalVar1 ... SHORT[i] = something; 在这种情况下,您不应 ...
  • 公共静态变量的行为就像那样。 如果您想要在页面回发期间保持_Total的值,请考虑以下内容 public decimal _Total { get { return (decimal) ViewState["_total"]; } set { ViewState["_total"] = decimal; } } A public static variable will behave like that. If what you want is to maintain the value of ...
  • 有,但有一个棘手的方法来实现你的目标: 变量是私有的,仅对某些元素可用。 您的功能模板可以访问它。 在头文件中定义的类中使用私有静态变量,并使您的函数/类模板成为此类的朋友。 YourFile.h class PrivateYourFileEntities { private: static const int SomeVariable; // ... other variables and functions template friend class A; ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)