美文网首页
深度学习笔记(1)基本运算

深度学习笔记(1)基本运算

作者: 无事扯淡 | 来源:发表于2017-03-13 00:55 被阅读0次

本笔记会认识一下tensorflow,numpy和matplotlib

1.numpy

numpy是一个数学运算库,基本的结构是数组。

  • 一个简单的数组
import numpy as np
a = np.array([1,2,3,4])
b = np.array(range(10))
#a.shape=(4,)
#b.shape=(10,)
#b.dtype=type('int64')
  • 数组操作
    默认情况下上面的数组是一维的,当然也可以修改,数据类型默认是整数64位。
c = np.array(range(10)).reshape(2,5)
c.astype(np.int32)

列选择

a = np.array([[1,2,3],[4,5,6]])
a[:,1]
#array([2,5])
#行选择直接用a[0]或者a[0,:]
  • 常用的数组初始化函数
np.zeros((2,2))
#array([[ 0.,  0.],
#       [ 0.,  0.]])
np.ones((2,2))
#array([[ 1.,  1.],
#       [ 1.,  1.]])
np.random.rand(2,2)
#array([[ 0.40081   ,  0.93288444],
#       [ 0.33550452,  0.98428802]])
np.random.randint(1,5,(2,3))
#array([[3, 4, 4],
#       [4, 1, 4]])
np.linspace(1,4,num=50)
#产生五十个数(等分)

注意上面数组维数输入参数的区别。

  • 常见运算
a = np.array([1,2])
b = np.array([1,2])
a*b
#[1,4]

上面的计算结果可以确认这种乘法可不是矩阵乘法运算,看看下面的代码:

b = b.reshape(2,1)
a*b
#array([[1, 2],
#       [2, 4]])
b = b.reshape(1,2)
a*b
#array([[1, 4]])

算术运算:

a = np.array([1,2])
#array([ 2.71828183,  7.3890561 ])
1/a
#[1,0.5]
a+1
#[2,3]

np重载了一些运算符号。

2.tensorflow

tensorflow一个非常重要的概念就是张量(tensor)和计算图。
一段简单的代码来计算加法运算:

import tensorflow as tf
a  = tf.constant([1,2,3])
b = tf.constant(1)
sess = tf.InteractiveSession()
sess.run(a+b)
#array([4, 5, 6], dtype=int32)

要计算运算值,这里有个会话的概念(session)。

x = tf.placeholder(tf.float32, shape=(1, 1))
y = tf.matmul(x,x)
sess.run(y,feed_dict={x:np.array([1]).reshape((1,1))}
#array([[ 1.]], dtype=float32)

矩阵乘法,需要注意维数和数据类型,tensorflow不支持int64。placeholder在使用前必须要用feed_dict赋值。

3. matplotlib

import matplotlib.pyplot as plt
%matplotlib inline
#plot绘制线
#scatter用来绘制点

上面的代码我引入了matplotlib,这里要注意的是后面那句代码用来在notebook中显示绘图。

4. 一个综合例子

x1 = np.random.rand(100,2)*6
x2 = np.random.rand(100,2)*-6
y1 = np.ones((100,1))
y2 = np.zeros((100,1))
x_ = np.vstack((x1,x2))
y_ = np.vstack((y1,y2))
x_ = x_.astype(np.float32)
y_ = y_.astype(np.float32)
b1 = tf.Variable(tf.zeros([1,1]))
W1 = tf.Variable(tf.random_uniform([2,1],-1.0,1.0))
y1 = tf.nn.relu(tf.matmul(x_,W1)+b1)
b2 = tf.Variable(tf.zeros([1,1]))
W2 = tf.Variable(tf.random_uniform([1,1],-1.0,1.0))
y2 = tf.nn.sigmoid(tf.matmul(y1,W2)+b2)
cross_entropy = -tf.reduce_sum(y_*tf.log(y2))
train_step = tf.train.GradientDescentOptimizer(0.03).minimize(cross_entropy)

相关文章

网友评论

      本文标题:深度学习笔记(1)基本运算

      本文链接:https://www.haomeiwen.com/subject/lketnttx.html