我想将计算后的批处理文件转换为int32 我不断收到这个错误 我收到无效错误,如何转换批处理文件,该文件是 将输入矩阵从float转换为int32,如何更改矩阵点积的形状 从float到int32。请帮助
InvalidArgumentError:无法计算AddV2,因为输入#1(从零开始)应为int32张量,但为浮点张量[Op:AddV2]名称:add /
请参见下面的代码,这是来自Google团队的示例代码
try:
#% tensorflow_version only exist in colab
% tensorflow_version 2.x
except Exception:
pass
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow.keras import Model
from mpl_toolkits.mplot3d import Axes3D
def make_noisy_data(m=0.1,b = 0.3, n=100):
x = tf.random.uniform(shape=(n,))
noise = tf.random.normal(shape=(len(x),),stddev=0.01)
y = m*x + b + noise
return x,y
x_train, y_train = make_noisy_data()
plt.plot(x_train, y_train, 'b.')
#define variables for ourmodel
m = tf.Variable(0.)
b = tf.Variable(0.)
#predict y given x
def predict(x):
y = m*x + b
return y
#our Loss will be the squared difference between the predicted
def squared_error(y_pred,y_true):
return tf.reduce_mean(tf.square(y_pred-y_true))
#calculate Loss before training
loss = squared_error(predict(x_train), y_train)
print("starting Loss", loss.numpy())
#use gradient descent to gradually improve our guest for loss
learning_rate = 0.05
steps = 200
for i in range(steps):
with tf.GradientTape() as tape:
predictions = predict(x_train)
loss = squared_error(predictions,y_train)
gradients = tape.gradient(loss,[m,b])
m.assign_sub(gradients[0]*learning_rate)
b.assign_sub(gradients[1]*learning_rate)
if i % 20 ==0:
print("step %d, loss %f" % (i,loss.numpy()))
#plot the best fit
plt.plot(x_train,y_train,'b.')
plt.plot(x_train,predict(x_train),'r')
ms = np.linspace(-1,1)
bs = np.linspace(-1,1)
m_mesh, b_mesh = np.meshgrid(ms,bs)
def loss_for_values(m,b):
y= m* x_train + b
loss = squared_error(y,y_train)
return loss
zs = np.array([loss_for_values(m,b) for (m,b) in zip(np.ravel(m_mesh),np.ravel(b_mesh))])
z_mesh = zs.reshape(m_mesh.shape)
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111,projection= '3d')
ax.plot_surface(m_mesh,b_mesh,z_mesh,color='r',alpha=0.06)
#At this point we have an error surface. Now we’ll need a history of the gradient decent steps
# Lets retrain the model here, keeping track of m,b and loss at each stage.
m = tf.Variable(-5)
b = tf.Variable(-0.75)
history=[]
x_train = tf.cast(x_train,tf.int32)
for i in range(steps):
with tf.GradientTape() as tape:
predictions = predict(x_train)
loss = squared_error(predictions, y_train)
history.append((m.numpy(),b.numpy(),loss.numpy()))
m.assign_sub(gradient[0]*learning_rate)
b.assign_sub(gradient[1]*learning_rate)
#plot the trajectory
ax.plot([h[0] for h in history],[h[1] for h in history], [h[2] for h in history], marker
='0')
ax.set_xlabel('m',fontsize=18,labelpad = 20)
ax.set_ylabel('b',fontsize=18,labelpad = 20)
ax.set_tlabel('loss',fontsize=18,labelpad = 20)
ax.view_init(elev=22, azim =28)