TensorFlow解決分類問題 示例 命令解釋

2021-10-03 15:07:28 字數 1860 閱讀 5271

shape:

對於輸入x.shape= [樣本數,單個樣本的特徵長度(打平或不打平)]。

對於輸出y.shape=[樣本數,輸出數]。

import  os

os.environ['tf_cpp_min_log_level']='2'

import tensorflow as tf

from tensorflow import keras

from tensorflow.keras import layers, optimizers, datasets

# 前乙個tuple為訓練集,後乙個tuple為測試集。x為資料,y為型別資料。

(x, y), (x_val, y_val) = datasets.mnist.load_data() # 載入資料集

x = tf.convert_to_tensor(x, dtype=tf.float32) / 255. # 轉換成張量,並歸一化

y = tf.convert_to_tensor(y, dtype=tf.int32) # 轉換為張量

y = tf.one_hot(y, depth=10) # one-hot編碼(對應位置為1,其它位置為0)

print(x.shape, y.shape)

train_dataset = tf.data.dataset.from_tensor_slices((x, y)) # 構建資料集物件

print(train_dataset)

train_dataset = train_dataset.batch(200) # 批量訓練

print(train_dataset)

model = keras.sequential([

layers.dense(512, activation='relu'),

layers.dense(256, activation='relu'),

layers.dense(10)])

optimizer = optimizers.sgd(learning_rate=0.001)

def train_epoch(epoch):

# step4.loop

for step, (x, y) in enumerate(train_dataset):

with tf.gradienttape() as tape:

# [b, 28, 28] => [b, 784]

x = tf.reshape(x, (-1, 28*28)) # 鋪平

# step1. compute output

# [b, 784] => [b, 10]

out = model(x)

# step2. compute loss

loss = tf.reduce_sum(tf.square(out - y)) / x.shape[0]

#print(x.shape) = (200,784)

# step3. optimize and update w1, w2, w3, b1, b2, b3

grads = tape.gradient(loss, model.trainable_variables)

# w' = w - lr * grad

if step % 100 == 0:

print(epoch, step, 'loss:', loss.numpy())

def train():

for epoch in range(5):

train_epoch(epoch)

if __name__ == '__main__':

train()

解決問TensorFlow和Coursera的問題

在windows的host檔案 位置在c windows system32 drivers etc hosts 末尾新增如下內容 tensorflow start 64.233 188 121 www.tensorflow.org tensorflow end開啟cmd,輸入如下命令 這一步是所有網...

tensorflow 神經網路解決二分類問題

import tensorflow as tf from numpy.random import randomstate 定義訓練資料batch大小 batch size 8 定義神經網路的引數 w1 tf.variable tf.random normal 2,3 stddev 1,seed 1 ...

Tensorflow 多分類問題

import requests import numpy as np 複製 r requests.get 複製 with open iris.data w as f f.write r.text 複製 import pandas as pd 複製 data pd.read csv iris.data...