娣卞害瀛︿範_1_Tensorflow_1

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了娣卞害瀛︿範_1_Tensorflow_1相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e8%83%bd%e5%8a%9b' title='鑳藉姏'>鑳藉姏   閮ㄥ垎   fine   鍒涘缓   ora   鍒楄〃   妯″潡   check   

# 娣卞害瀛︿範
#   鍥惧儚璇嗗埆,鑷劧璇█澶勭悊
#   鏈哄櫒瀛︿範                娣卞害瀛︿範
#   鍒嗙被:绁炵粡缃戠粶(绠€鍗?      绁炵粡缃戠粶(娣卞害)
#   鍥炲綊                    鍥惧儚:鍗风Н绁炵粡缃戠粶
#                           鑷劧璇█澶勭悊:寰幆绁炵粡缃戠粶
# cpu:杩愯鎿嶄綔绯荤粺,澶勭悊涓氬姟,璁$畻鑳藉姏涓嶆槸鐗瑰埆绐佸嚭
# gpu:涓撻棬涓鸿绠楄璁$殑
import tensorflow as tf
a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a,b) # 鍦╯ession澶栬竟鎵撳嵃鏃跺彧鑳芥煡鐪嬪璞?/span>
# 绋嬪簭鐨勫浘 a,b,sum1涔熸湁graph
graph = tf.get_default_graph()
print(a.graph)
print(graph)
# session()杩愯榛樿鐨勫浘,褰撹繍琛岀殑鍏冪礌涓嶆槸榛樿鍥剧殑鏃跺€?浼氭姤閿?/span>
with tf.Session() as sess:
    print(sess.run(sum1)) # 杈撳嚭鍊?/span>
# 鍒涘缓鏂扮殑鍥?/span>
g = tf.Graph()
with g.as_default():
    c = tf.constant(11.0)
    print(c.graph)  # 涓庝笂杈圭殑鍥句笉鍚?/span>

# 鍥剧▼搴忕殑绌洪棿,鍙橀噺,绾跨▼绛夎祫婧愰兘鍦ㄥ浘涓?/span>
# 浼氳瘽杩愯鍥剧殑绋嬪簭,
# tf.Session(graph=c) 鎸囧畾鍥捐繍琛? 閲岃竟run鐨勬椂鍊欒娉ㄦ剰
#   session.run鐨勪綔鐢?鍚姩鏁翠釜鍥?/span>
#   session.close:鍏抽棴,閲婃斁璧勬簮娌?/span>
# Session涓殑鍙傛暟
#   tf.Session(config=tf.ConfigProto(log_device_placement=True))
# 浜や簰寮弒ession:tf.InteractiveSession()
#   璋冪敤鍚?涓嶇敤Session() 涓嶅悓run 鐩存帴a.eval()涔熷彲
#   鍏跺疄鍙鏈変細璇濈殑涓婁笅鏂囩幆澧?灏卞彲浠ヤ娇鐢╡val()
# ===================================================
# 浼氳瘽鐨剅un()
# run(fetches,feed_dict=None,graph=None) 杩愯ops涓巘ensor
#   fetches 闇€瑕乺un鐨勫唴瀹?鏈夊涓椂浣跨敤[]
# 涓嶆槸op涓嶈兘run 渚?sum2 = 1+3
#   浣?sum3=1+tf.constant(3.0) 鍙互run(sum3)
# ========================================
# 瀹炴椂鎻愪緵鏁版嵁
# placeholder
#   tf.placeholder(dtype,shape=None,name=None)
#   plt = tf.placeholder(tf.float32,[2,3]) [None,3]涔熷彲
#   run(plt,feed_dict={plt:[[1,2,3],[4,5,6]]})
input1 = tf.placeholder(tf.float32)  # 鍙互璇存槸涓€涓崰浣嶇,浣跨敤鐨勬椂鍊欓渶瑕佷紶鍏ュ€?/span>
input2 = tf.placeholder(tf.float32)

output = input1*input2
with tf.Session() as sess: # 浼犲€肩殑鏃跺€欎娇鐢╢eed_dict 瀛楀吀 鍗犱綅绗﹀璞′綔涓洪敭,鍊奸渶瑕佷娇鐢╗] 鍖呭惈
    print(sess.run(output,feed_dict={input1:[7],input2:[2.6]}))
# =============================================================
# 寮犻噺tensor
# 灏唍umpy涓殑鏁扮粍灏佽涓簍ensor绫诲瀷
# tensor:鍚嶅瓧,shape,dtype
#   闃?缁村害
#   鏁版嵁绫诲瀷:tf.float32,64(鍏跺疄娌℃湁鎰忎箟,瀹為檯杩樻槸32) int8-64,uint8,string,bool
#   print(a.shape,a.name,a.op,a.graph)
#   0缁?() 1缁?(n) 2缁?(n,m) ...
# ======================================
# Numpy:reshape 鎶婂師鏉ョ殑鏁版嵁鐩存帴淇敼
# tensorflow涓?/span>
#   tf.reshape:鍒涘缓鏂扮殑寮犻噺 鍔ㄦ€佸舰鐘?/span>
#   tf.Tensor.set_shape:鏇存柊Tensor鐨勯潤鎬佸舰鐘?/span>
# 闈欐€佸舰鐘?(褰撴暟閲忎笉纭畾鏃跺彲浠?鍒囦笉鑳借法缁村害)
plt = tf.placeholder(tf.float32,[None,2])  # shape=(?,2)
plt.set_shape([3,2])  # shape=(3,2)
plt.set_shape([4,2])  # 姝ゆ椂涓嶈兘淇敼
# 鍔ㄦ€佸舰鐘?(娉ㄦ剰鍏冪礌涓暟涓嶈兘鏀瑰彉,鍙法缁村害)
new_plt=tf.reshape(plt,[2,3]) # shape=(2,3)
# ==========================================
# 鏈夐粯璁ゅ€肩殑寮犻噺
#   tf.zero(shape,dtype=tf.float32,name=None) 鍏ㄤ负0
#   tf.ones(shape,dtype=float32,name=None) 鍏ㄤ负1
#   tf.constant(value,dtype=None,shape=None,name=None) 甯搁噺寮犻噺
#   tf.random_normal(shape,mean=0.0,stddev=1.0,dtype=float32,seed=None,name=None)  鐢辨澶垎閮ㄧ殑闅忔満鍊肩粍鎴愮殑鐭╅樀
# ==========================
# 寮犻噺鐨勭被鍨嬪彉鎹?/span>
# tf.string_to_number(string_tensor,out_type=None,name=None) 绛?/span>
# tf.cost(x,dtype,name=None) 涓囪兘杞崲
#   tf.cost(鍘熸潵鏁版嵁,鏂扮被鍨?
# ===========================
# 鏁版嵁鎷兼帴 a=[[1,2,3],[4,5,6]] b = [[7,8,9],[10,11,12]]
# tf.concat([a,b],axis=1) 鍚堝苟鍚庡彉涓?鍒?/span>
# api https://www.tensorflow.org/versions/r1.0/api_guides/python/math_ops
# ===================================================
# 鍙橀噺op 鍙互鎸佷箙鍖? 鏅€氱殑寮犻噺op涓嶈
# 鍙橀噺op闇€瑕佸湪浼氳瘽涓繍琛屽垵濮嬪寲
# name鍙傛暟:鍦╰ensorboard涓樉绀哄悕瀛?鍙互璁╃浉鍚宱p鍚嶅瓧鐨勬暟鎹繘琛屽尯鍒?/span>
#   璁剧疆鍚?Tensor("Variable") ---->Tensor("璁剧疆鐨刵ame")
a = tf.constant([1,2,3,4,5])
random = tf.random_normal([2,3],mean=0.0,stddev=1.0)
var = tf.Variable(initial_value=random,name=None,trainable=None)
print(a,var)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)  # 鍒濆鍖杘p
    print(sess.run([a,var]))  # 鍐嶆鎵撳嵃

# ====================================================
# 鍙鍖?/span>
# 妯″潡:summary
with tf.Session() as sess:
    sess.run(init)
    filewriter =  tf.summary.FileWriter(".",graph=sess.graph)
# 杩愯鍚庣敓鎴愭枃浠?姣忔杩愯閮戒細鐢熸垚鏂囦欢,
# tensorboard --logdir="鐢熸垚鐨勬枃浠舵墍鍦ㄧ殑鐩綍"    浼氬惎鍔ㄤ竴涓湇鍔″櫒,璁块棶鍗冲彲
# ===============================================
# 绾挎€у洖褰掑師鐞嗗強瀹炵幇
# 1,杞濂界壒寰佸拰鐩爣鍊?/span>
# 2,寤虹珛妯″瀷 妯″瀷鍙傛暟蹇呴』鏄彉閲?/span>
# 3,姹傛崯澶卞嚱鏁?璇樊  鍧囨柟璇樊
# 4,姊害涓嬮檷浼樺寲鎹熷け杩囩▼,鎸囧畾瀛︿範鐜?/span>
# ========杩愮畻api
# tf.matmul(x,w) 鐭╅樀杩愮畻
# tf.squqre(error) 骞虫柟 姣忎釜鏍锋湰璇樊骞虫柟
# tf.reduce_mean(error) 姣忎釜鍒楄〃骞冲潎鍊?/span>

# ===========姊害涓嬮檷api
# tf.train.GradientDescentOptimizer(learning_rate)
#   minimize
#   杩斿洖姊害涓嬮檷op
# ==============================================
# tensorflow 瀹炵幇绠€鍗曠殑绾挎€у洖褰?/span>
import tensorflow as tf
def myregression():
    """
    鑷疄鐜颁竴涓嚎鎬у洖褰掗娴?
    """
    # 1,鍑嗗鏁版嵁, x 鐗瑰緛鍊糩100,10] y鐩爣鍊糩100]
    # 鍑嗗x
    x = tf.random_normal([100,1],mean=1.75,stddev=0.5,name="x_data")
    # 鍑嗗y,鑷畾涔夊嚭瀹為檯鐨剋,b
    # 鐭╅樀鐩镐箻蹇呴』鏄簩缁寸殑
    y_true= tf.matmul(x,[[0.7]])+0.8
    # 2,寤虹珛妯″瀷
    # 闅忔満鐨勬潈閲嶄笌鍋忕疆,璁╄繘琛屼紭鍖?/span>
    # 鍙兘浣跨敤鍙橀噺瀹氫箟,trainable鎺у埗璇ュ彉閲?璁粌鐨勬椂鍊欐槸鍚﹁鍙樺寲
    weight = tf.Variable(tf.random_normal([1,1],mean=0.0,stddev=0.75),trainable=True)
    bias = tf.Variable(0.0,name="b")
    y_predcit = tf.matmul(x,weight)+bias
    # 3,寤虹珛鎹熷け鍑芥暟,鍧囨柟璇樊
    loss = tf.reduce_mean(tf.square(y_true-y_predcit))
    # 4,姊害涓嬮檷浼樺寲鎹熷け
    youhua = tf.train.GradientDescentOptimizer(0.1)  # 涓€鑸?-1涔嬮棿涓嶈兘澶ぇ,
    # 涔熷彲2,3,10绛?鑻ュお澶у彲鑳戒細鍑虹幇nan:姊害鐖嗙偢
    #       瑙e喅鏂规:閲嶆柊璁捐缃戠粶,璋冩暣瀛︿範鐜?浣跨敤姊害鎴柇,浣跨敤婵€娲诲嚱鏁?/span>
    train_op = youhua.minimize(loss)
    # 鏀堕泦tensor
    tf.summary.scalar("losses",loss) # 鍦╰ensorborad涓?scalars 浼氭樉绀哄湪瀛︿範鐨勮繃绋嬩腑loss鐨勫彉鍖栨洸绾?/span>
    tf.summary.histogram("weights",weight)
    # 瀹氫箟鍚堝苟tensor鐨刼p
    merged=tf.summary.merge_all()
    saver = tf.train.Saver()

    init = tf.global_variables_initializer()
    # 浼氳瘽杩愯
    with tf.Session() as sess:
        sess.run(init)
        # 鎵撳嵃涓嶄紭鍖栫殑train_op
        print(sess.run([weight,bias]))
        filewrite = tf.summary.FileWriter(".",graph=sess.graph)
        # 妯″瀷鎭㈠
        # 妯″瀷鏂囦欢瀛樺湪
        # saver.restore("sess","璺緞")

        # 寰幆杩愯浼樺寲
        for i in range(1000):

            sess.run(train_op)
            # 杩愯鍚堝苟鐨則ensor
            summary = sess.run(merged)
            filewrite.add_summary(summary,i)
            print("绗瑊}娆?/span>".format(i),sess.run([weight, bias]))
        saver.save(sess,"./reserve/model")
if __name__ =="__main__":
    myregression()
# ========================
# tensorflow鍙橀噺浣滅敤鍩焧f.variable_scope()鍒涘缓鎸囧畾鍚嶅瓧鐨勫彉閲忎綔鐢ㄥ煙
# 涓嶅悓鐨勯儴鍒嗘斁鍦ㄤ笉鍚岀殑浣滅敤鍩熶笅,tensorflowboard涓璯raph 浼氭洿鍔犳竻鏅?浣滅敤鍒嗘槑
with tf.variable_scope("name"):
    pass

# 澧炲姞鍙橀噺鏄剧ず
#   娣诲姞鏉冮噸鍙傛暟,鎹熷け鍊肩瓑鍦╰ensorborad涓樉绀?/span>
#   1,鏀堕泦鍙橀噺
#       tf.summary.scalar(name="",tensir)鏀堕泦瀵逛簬鎹熷け鍑芥暟鍜屽噯纭巼绛夊崟鍊煎彉閲?name涓哄彉閲忓€?tensor涓哄€?/span>
#       tf.summary.histogram(name="",tensor) 鏀堕泦楂樼淮搴︾殑鍙橀噺鍙傛暟
#   2,鍚堝苟鍙橀噺鍐欏叆浜嬩欢鏂囦欢
#       merged = tf.summary.merge_all()
#       杩愯鍚堝苟:summary=sess.run(merged) 姣忔杩唬閮介渶瑕佽繍琛?/span>
#       娣诲姞:FileWriter.add_summary(summary,i)i琛ㄧず绗嚑娆¤凯浠?/span>
# ========================
# tensorflow鍙橀噺浣滅敤鍩焧f.variable_scope()鍒涘缓鎸囧畾鍚嶅瓧鐨勫彉閲忎綔鐢ㄥ煙
# 涓嶅悓鐨勯儴鍒嗘斁鍦ㄤ笉鍚岀殑浣滅敤鍩熶笅,graph 浼氭洿鍔犳竻鏅?浣滅敤鍒嗘槑
with tf.variable_scope("name"):
    pass
# 妯″瀷鐨勪繚瀛樹笌鍔犺浇
saver = tf.train.Saver(var_list=None,max_to_keep=5)
# var_list:鎸囧畾瑕佷繚瀛樺拰杩樺師鐨勫彉閲?浣滀负涓€涓猟ict鎴栧垪琛ㄤ紶閫?/span>
# max_to_keep:鎸囩ず瑕佷繚鐣欑殑鏈€杩戞鏌ョ偣鏂囦欢鐨勬渶澶ф暟閲?鍒涘缓鏂版枃浠舵椂,鍒犻櫎鏃ф枃浠?淇濈暀鏈€鏂扮殑5涓?/span>
# 鏂囦欢鏍煎紡:checkpoint鏂囦欢
saver.save("sess瀵硅薄","璺緞/鏂囦欢鍚嶅瓧")
# 绗竴娆′繚瀛?/span>
#   checkpoint:璁板綍妯″瀷鍚嶅瓧,鏂囦欢璺緞
#   name.data-00000-of-00001 鏁版嵁瀛樺偍鏂囦欢
#   name.index name.meta
# 妯″瀷鐨勫姞杞?/span>
#   saver.restore(sess,"璺緞")
#   鍦╳ith鏀惧叆浼氳瘽涓?寮€濮嬩紭鍖栧墠
# ===================================
# 鑷畾涔夊懡浠よ鍙傛暟
# 1, 棣栧厛瀹氫箟鏈夊摢浜涘弬鏁伴渶瑕佸湪杩愯鏃舵寚瀹?/span>
# 2,绋嬪簭褰撲腑鑾峰彇瀹氫箟鐨勫懡浠よ鍙傛暟
# 鍚嶅瓧,榛樿鍊?璇存槑
# 浠ュ墠鐨勭増鏈?/span>
# tf.app.flags.DEFINE_integer("max_step",100,"妯″瀷璁粌鐨勬鏁?)
# tf.app.flags.FLAGS.max_step 鑾峰彇鏁版嵁
# 鏂扮増
flags = tf.flags.FLAGS # 瀹氫箟瀵硅薄
tf.flags.DEFINE_integer("max_step",100,"妯″瀷璁粌鐨勬鏁?/span>")
tf.flags.DEFINE_string("file_path","","鏂囦欢璺緞")
tf.flags._FlagValuesWrapper # 鍒濆鍖?/span>
flags.max_step=100 # 淇敼 鎴栬幏鍙?/span>
# 瀹氫箟瀹屾垚鍚? 杩愯鏂囦欢鏃?python  xx.py --max-step=500 鍗冲彲浼犲叆,瀛楃涓查渶瑕佸姞寮曞彿

 

以上是关于娣卞害瀛︿範_1_Tensorflow_1的主要内容,如果未能解决你的问题,请参考以下文章

鍏ラ棬娣卞害瀛︿範锛岀悊瑙g缁忕綉缁溿€佸弽鍚戜紶鎾畻娉曟槸绗竴鍏?/h1>

娣卞害瀛︿範鍘熺悊璇﹁В鍙奝ython浠g爜瀹炵幇

娣卞害瀛︿範涓嶯LP

Github 9.9K Star鐨勩€婄缁忕綉缁滀笌娣卞害瀛︿範銆嬶紙闄勪笅杞斤級

鍥惧儚璇嗗埆VPU鈥斺€旀槗鐢ㄧ殑宓屽叆寮廇I鏀寔娣卞害瀛︿範骞冲彴浠嬬粛