安装
conda create -n tf python
pip install tensorflow
若安装速度慢可使用
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple
检查是否安装成功
打开python输入
import tensorflow as tf
tf.__version__
输出如下安装成功
最新版本为2.13.0
张量
张量: TensorFlow中所有数据的表示形式
首先导入库
import tensorflow as tf
tf.compat.v1.enable_eager_execution()#用来输出张量的值
张量计算
生成张量
a=tf.constant([1.0,2.0])#a是一个张量
b=tf.constant([2.0,3.0])#b是一个张量
加法
result=a+b#直接相加
乘法
c=tf.matmul(tf.reshape(a,(1, 2)),tf.reshape(a,(2, 1)))
输出结果
输出一个张量,输出为一个Tensor
print("result=",result)
若要直接输出张量的值
在程序开头加上tf.compat.v1.enable_eager_execution()
然后使用
print("result=",result.numpy())
获取张量维度
print("shape=",result.get_shape())#获取张量维度信息
变量
变量: 张量的一种
赋值方式如下
weights=tf.Variable(tf.random.normal([2, 3],stddev=2))#产生一个2×3的矩阵均值为0,方差为2
print("weights=",weights.numpy())
biases=tf.Variable(tf.zeros([3]))#产生一个初始值为0,长度为3的变量
print("biases=",biases.numpy())
#通过其他变量的初始值来初始化新的变量
w2=tf.Variable(tf.random.normal([2, 3],stddev=2))
w2=w2.assign(weights)
print("w2=",w2.numpy())
神经网络
使用TensorFlow构建一个具有一个隐藏层的前馈神经网络:
定义训练数据
首先定义了训练数据x_train和对应的标签y_train
x_train = tf.constant([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=tf.float32)
y_train = tf.constant([[0], [1], [1], [0]], dtype=tf.float32)
定义神经网络模型
使用tf.keras.Sequential构建一个顺序模型,该模型具有一个具有3个神经元和Sigmoid激活函数的隐藏层,以及一个具有1个神经元和Sigmoid激活函数的输出层。
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=3, activation='sigmoid', input_shape=(2,)),
tf.keras.layers.Dense(units=1, activation='sigmoid')
])
编译模型
使用compile方法编译模型,指定优化器、损失函数和评估指标。在这里,我们使用Adam优化器、交叉熵损失和准确率作为评估指标。
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.1),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=['accuracy'])
训练模型
使用fit方法对模型进行训练,将训练数据和标签作为输入,并指定训练的迭代次数。
model.fit(x_train, y_train, epochs=1000, verbose=0)
使用模型进行预测
使用训练好的模型对训练数据进行预测,并打印预测结果。
predictions = model.predict(x_train)
print(predictions)
以下是一个简单的神经网络的代码:
import tensorflow as tf
# 定义训练数据
x_train = tf.constant([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=tf.float32)
y_train = tf.constant([[0], [1], [1], [0]], dtype=tf.float32)
# 定义神经网络模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=3, activation='sigmoid', input_shape=(2,)),
tf.keras.layers.Dense(units=1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.1),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=1000, verbose=0)
# 使用模型进行预测
predictions = model.predict(x_train)
print(predictions)