1 關(guān)于tensorflow的安裝 參看官方文檔
#使用 [Homebrew](https://brew.sh/) 軟件包管理器安裝:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
brew update
brew install python # Python 3
sudo pip3 install -U virtualenv # system-wide install
#創(chuàng)建一個(gè)新的虛擬環(huán)境空繁,方法是選擇 Python 解釋器并創(chuàng)建一個(gè) ./venv 目錄來存放它:
virtualenv --system-site-packages -p python3 ./venv
#使用特定于 shell 的命令激活該虛擬環(huán)境:
source ./venv/bin/activate # sh, bash, ksh, or zsh
(venv)$ pip install --upgrade pip
#安裝tensorflow
(venv)$ pip install --upgrade tensorflow
2.安裝vs code
a. 安裝插件 Python
b. (工作目錄)/.vscode/settings.json 文件設(shè)置如下
{
"python.pythonPath": "/Users/Apple/venv/bin/python3",
"python.autoComplete.extraPaths": [
"/Users/mirage/venv/lib/python3.7/site-packages/"
]
}
c. (工作目錄)/.vscode/launch.json 文件設(shè)置如下
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"pythonPath": "${config:python.pythonPath}",
"request": "launch",
//"program": "${file}",
"program": "${workspaceRoot}/chapter01.py",
"console": "integratedTerminal"
}
]
}
3. 示例代碼
import tensorflow as tf
import numpy as np
#實(shí)例化一個(gè)Sequential票顾,并添加一個(gè)一層的全連接神經(jīng)網(wǎng)絡(luò)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(input_dim=1,units=1))
#編譯神經(jīng)網(wǎng)絡(luò)模型 損失函數(shù)用mse韩玩,隨機(jī)梯度下降為optimizer
model.compile(loss='mse', optimizer='sgd')
#初始化數(shù)據(jù)
#生成10個(gè)數(shù)據(jù) 從1到10
X = np.linspace(1, 10, 10)
Y = 2*X
#訓(xùn)練數(shù)據(jù) verbose=1 為顯示進(jìn)度信息 epochs=5 訓(xùn)練5期 validation_split表示分離20%的數(shù)據(jù)用來驗(yàn)證
model.fit(X, Y, verbose=1, epochs=5, validation_split=0.2)
#保存數(shù)據(jù) 以及加載數(shù)據(jù)
#filename = 'model.h5'
#model.save(filename)
#model = tf.keras.models.load_model(filename)
#驗(yàn)證數(shù)據(jù)
x = tf.constant([1, 2, 3, 4])
print(model.predict(x))
#輸出:[[2.0426083] [4.0222816] [6.0019546] [7.981628 ]]
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者