新手python、tensorflow项目中遇到的常见问题(持续更新)

 

python版本:3.6

1.jupyter notebook中创建文件夹

概述:os.makedirs() 方法用于递归创建目录。

语法:

   os.makedirs(path, mode=0o777)

参数:

      path -- 需要递归创建的目录。

      mode -- 权限模式。

例子

import os

os.makedirs('/abc')
print('done')

jupyter notebook默认打开的C盘根目录,不设定具体目录路径,文件夹保存在C盘根目录。

2.urllib库的urlretrieve()方法下载网络文件到本地

模块:from urllib.request import urlretrieve

语法:

       urlretrieve(url, filename=None, reporthook=None, data=None)

    官网:   retrieve(url[, filename[, reporthook[, data]]])

参数:

      url:外部或者本地url文件

      filename:保存到本地的文件名或者路径(如果未指定该参数,urllib会生成一个临时文件来保存数据)

      reporthook:文件传输时的回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调,我们可以利用这                               个回调函数来显示当前的下载进度。

      data:post提交到服务器的数据。

该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。The return value is a tuple consisting of a local filename and either a mimetools.Message object containing the response headers (for remote URLs) or None (for local URLs).

3.pickle — Python object serialization

The pickle module implements binary protocols for serializing and de-serializing a Python object structure.(pickle用于序列号和反序列化)

To serialize an object hierarchy, you simply call the dumps() function. Similarly, to de-serialize a data stream, you call the loads() function. However, if you want more control over serialization and de-serialization, you can create a Pickler or an Unpickler object, respectively.(dumps()用来序列化, loads() 用来反序列化)

1)pickle.dump(objfileprotocol=None*fix_imports=True)

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file,protocol).dump(obj).(将obj的pickled表示写入打开的文件对象文件。)

2)pickle.load(file*fix_imports=Trueencoding="ASCII"errors="strict")

Read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified therein. This is equivalent to Unpickler(file).load().(从打开的文件对象文件中读取pickle对象表示,并返回其中指定的重构对象层次结构)

4. with tf.name_scope()

5.tf.random_nomal()

用于从服从指定正太分布的数值中取出指定个数的值.

tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

  • shape: 输出张量的形状,必选
  • mean: 正态分布的均值,默认为0
  • stddev: 正态分布的标准差,默认为1.0
  • dtype: 输出的类型,默认为tf.float32
  • seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样
  • name: 操作的名称

可以参考https://blog.csdn.net/dcrmg/article/details/79028043,包含示例说明。

6.tf.random_uniform 函数.   从均匀分布中输出随机值.

random_uniform( shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None )

7.tf.concat()详解

tensorflow中用来拼接张量的函数tf.concat(),用法:

tf.concat([tensor1, tensor2, tensor3,...], axis)

先给出tf源代码中的解释:

  t1 = [[1, 2, 3], [4, 5, 6]]
  t2 = [[7, 8, 9], [10, 11, 12]]
  tf.concat([t1, t2], 0)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  tf.concat([t1, t2], 1)  # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
 
  # tensor t3 with shape [2, 3]
  # tensor t4 with shape [2, 3]
  tf.shape(tf.concat([t3, t4], 0))  # [4, 3]
  tf.shape(tf.concat([t3, t4], 1))  # [2, 6]

axis表示你在哪个维度上进行连接,他是整数,从0开始计数,0表示第一个维度,1表示第二个维度......

tensor1....是一个列表。列表里面是要连接的矩阵或者数组。

我理解的要点是,在哪个维度上连接,那么这个维度肯定会增加。

从上面的例子可以看出,axis=0,在第一个维度上连接,那么第一个维度肯定增加,也就是行会增多。

8. tf.contrib.layers.fully_connected()

官网:

tf.contrib.layers.fully_connected(
    inputs, 
    num_outputs,
    activation_fn=tf.nn.relu,
    normalizer_fn=None,
    normalizer_params=None,
    weights_initializer=initializers.xavier_initializer(),
    weights_regularizer=None,
    biases_initializer=tf.zeros_initializer(),
    biases_regularizer=None,
    reuse=None,
    variables_collections=None,
    outputs_collections=None,
    trainable=True,
    scope=None
)

Args:
1.inputs: A tensor of at least rank 2 and static value for the last dimension; i.e. [batch_size, depth], [None, None, None, channels].
2.num_outputs: Integer or long, the number of output units in the layer.
3.activation_fn: Activation function. The default value is a ReLU function. Explicitly set it to None to skip it and maintain a linear activation.
4.normalizer_fn: Normalization function to use instead of biases. If normalizer_fn is provided then biases_initializer and biases_regularizer are ignored and biases are not created nor added. default set to None for no normalizer function

9. tf.reduce_sum

reduce_sum(
    input_tensor,
    axis=None,
    keep_dims=False,
    name=None,
    reduction_indices=None
)

 reduce_sum 是 tensor 内部求和的工具。其参数中:

1). input_tensor 是要求和的 tensor

2). axis 是要求和的 rank,如果为 none,则表示所有 rank 都要仇和

3). keep_dims 求和后是否要降维

4). 这个操作的名称,可能在 graph 中 用

5). 已被淘汰的,被参数 axis 替代

示例如下:

x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x, 0)  # 对 tensor 的 0 级进行求和,[1,1,1] + [1,1,1] =  [2 2 2]
tf.reduce_sum(x, 1)  # 对 tensor 的 1 级进行仇和,[1+1+1, 1+1+1] = [3 3]
tf.reduce_sum(x, 1, keep_dims=True)  # 对第 1 级进行求和,但不降维, [[3] [3]]
tf.reduce_sum(x, [0, 1])  # 0 级和 1级都要求和,6
tf.reduce_sum(x)  # 因为 x 只有 2 级,所以结果同上一个,6

10.tf.reshape(tensor,shape,name=None)

这里主要想说明下-1的作用:

-1 的应用:-1 表示不知道该填什么数字合适的情况下,可以选择,由python通过a和其他的值3推测出来,比如,这里的a 是二维的数组,数组中共有6个元素,当使用reshape()时,6/3=2,所以形成的是3行2列的二维数组,可以看出,利用reshape进行数组形状的转换时,一定要满足(x,y)中x*y=数组的个数。
 

>>>a = np.array([[1,2,3],[4,5,6]])
>>>np.reshape(a,(3,-1)) 
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.reshape(a,(1,-1))
array([[1, 2, 3, 4, 5, 6]])
>>> np.reshape(a,(6,-1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.reshape(a,(-1,1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

11.python中的with语句

with语句适用于对资源进行访问的场景,确保不论使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭,线程中锁的自动获取和释放。

with zipfile.ZipFile(sava_path) as zf:
    zf.extractall(data_path)

12.python中的ZipFile

官网解释:https://docs.python.org/3/library/zipfile.html#zipfile-objects

class zipfile.ZipFile(filemode='r'compression=ZIP_STOREDallowZip64=Truecompresslevel=None)

Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object.

打开一个zip文件,对其操作,可以参考11的例子形式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值