本筆記會(huì)認(rèn)識(shí)一下tensorflow乙埃,numpy和matplotlib
1.numpy
numpy是一個(gè)數(shù)學(xué)運(yùn)算庫(kù)斤贰,基本的結(jié)構(gòu)是數(shù)組漫雕。
- 一個(gè)簡(jiǎn)單的數(shù)組
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')
- 數(shù)組操作
默認(rèn)情況下上面的數(shù)組是一維的还绘,當(dāng)然也可以修改窗价,數(shù)據(jù)類型默認(rèn)是整數(shù)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,:]
- 常用的數(shù)組初始化函數(shù)
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)
#產(chǎn)生五十個(gè)數(shù)(等分)
注意上面數(shù)組維數(shù)輸入?yún)?shù)的區(qū)別碰煌。
- 常見(jiàn)運(yùn)算
a = np.array([1,2])
b = np.array([1,2])
a*b
#[1,4]
上面的計(jì)算結(jié)果可以確認(rèn)這種乘法可不是矩陣乘法運(yùn)算,看看下面的代碼:
b = b.reshape(2,1)
a*b
#array([[1, 2],
# [2, 4]])
b = b.reshape(1,2)
a*b
#array([[1, 4]])
算術(shù)運(yùn)算:
a = np.array([1,2])
#array([ 2.71828183, 7.3890561 ])
1/a
#[1,0.5]
a+1
#[2,3]
np重載了一些運(yùn)算符號(hào)。
2.tensorflow
tensorflow一個(gè)非常重要的概念就是張量(tensor)和計(jì)算圖绅作。
一段簡(jiǎn)單的代碼來(lái)計(jì)算加法運(yùn)算:
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)
要計(jì)算運(yùn)算值芦圾,這里有個(gè)會(huì)話的概念(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)
矩陣乘法俄认,需要注意維數(shù)和數(shù)據(jù)類型个少,tensorflow不支持int64。placeholder在使用前必須要用feed_dict賦值眯杏。
3. matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
#plot繪制線
#scatter用來(lái)繪制點(diǎn)
上面的代碼我引入了matplotlib夜焦,這里要注意的是后面那句代碼用來(lái)在notebook中顯示繪圖。
4. 一個(gè)綜合例子
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)