2019.12.04
一、tensorflow學習
1.astype:
轉換數組的數據類型。
2.dtype:
一個用於說明數組數據類型的對象。返回的是該數組的數據類型。由於圖中的數據都爲整形,所以返回的都是int32。如果數組中有數據帶有小數點,那麼就會返回float64。
3.與莫煩的第一個tensorflow例子相似的例子
import tensorflow as tf
import numpy as np
# 使用 NumPy 生成假數據(phony data), 總共 100 個點.
x_data = np.float32(np.random.rand(2, 100)) # 隨機輸入
y_data = np.dot([0.100, 0.200], x_data) + 0.300
# 構造一個線性模型
#
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b
# 最小化方差
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# 初始化變量
init = tf.initialize_all_variables()
# 啓動圖 (graph)
sess = tf.Session()
sess.run(init)
# 擬合平面
for step in range(0, 201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
# 得到最佳擬合結果 W: [[0.100 0.200]], b: [0.300]
4.安裝tensorflow-gpu遇到的問題及總結
遇到的最主要的問題就是如下報錯
出現這個問題似乎是由於沒有dll.100這個動態鏈接庫,經過反覆試測試應該是CUDA和tensorflow-gpu的版本不匹配導致的。
最終安裝成功用的如下版本
CUDA:cuda_10.0.130_411.31_win10
cudnn:cudnn-10.0-windows10-x64-v7.6.4.38
tensorflow-gpu:1.14.0
共花費一天半的時間!!!!
5.一個好的tensorflow中文文檔
此文檔鏈接包含但不限於tensorflow的基本使用
以下是遇到的問題:
①.tf.Variable(initializer,name)
參數initializer是初始化參數,name是可自定義的變量名稱,用法如下:
結果如下:
②.tf.constant
③.tf.random_uniform
tf.random_uniform((4, 4), minval=low,maxval=high,dtype=tf.float32)))返回4*4的矩陣,產生於low和high之間,產生的值是均勻分佈的。
清晰描述tf.random_uniform用法
tf.random_normal與區別tf.random_uniform
④.numpy庫中rand(),randn(),randint(),random_integers()等random系函數的使用
⑤.tf.zeros
說白了,就是初始化的時候,用都0佔坑。
詳細鏈接
6.session的兩種打開形式
from __future__ import print_function
import tensorflow as tf
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1, matrix2) # matrix multiply np.dot(m1, m2)
# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# method 2
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
7.variable變量
在tensorflow中,變量的定義和c語言類似,需要手動指明name。要區別於python中變量的定義。
from __future__ import print_function
import tensorflow as tf
state = tf.Variable(0, name='cyq')
print(state.name)
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))
8.placeholder傳入值
placeholder()函數是在神經網絡構建graph(圖)的時候在模型中的佔位,此時並沒有把要輸入的數據傳入模型,它只會分配必要的內存。等建立session,在會話中,運行模型的時候通過feed_dict()函數向佔位符喂入數據。
from __future__ import print_function
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1: [7.], input2: [2.]}))