我正在尝试从我现有的 Angular 项目中运行的 tensorflow.js 网站获取 tensorflow.js 示例。我基本上是从网站上复制代码并将其集成到我的组件中,但我收到一条错误消息。
由于我是 Angular 的新手,所以我不知道如何修复错误。
export class MotionAnalysisComponent implements OnInit{
async run() {
// We want to predict the column "medv", which represents a median value of
// a home (in $1000s), so we mark it as a label.
const csvUrl = 'https://storage.googleapis.com/tfjs-examples/multivariate-linear-regression/data/boston-housing-train.csv';
const csvDataset = tf.data.csv(
csvUrl, {
columnConfigs: {
medv: {
isLabel: true
}
}
});
// Number of features is the number of column names minus one for the label column.
const numOfFeatures = (await csvDataset.columnNames()).length - 1;
// Prepare the Dataset for training.
const flattenedDataset =
csvDataset
.map(({xs, ys}) =>
{
// Convert xs(features) and ys(labels) from object form (keyed by
// column name) to array form.
return {xs:Object.keys(xs), ys:Object.keys(ys)};
})
.batch(10);
// Define the model.
const model = tf.sequential();
model.add(tf.layers.dense({
inputShape: [numOfFeatures],
units: 1
}));
model.compile({
optimizer: tf.train.sgd(0.000001),
loss: 'meanSquaredError'
});
// Fit the model using the prepared Dataset
return model.fitDataset(flattenedDataset, {
epochs: 10,
callbacks: {
onEpochEnd: async (epoch, logs) => {
console.log(epoch + ':' + logs.loss);
}
}
});
}
}
我收到以下两条错误消息:
类型“TensorContainer”上不存在属性“xs”
类型“TensorContainer”上不存在属性“ys”
最佳答案
问题
问题是 Datasets在 Tensorflow.js 中默认类型为 tf.data.Dataset<TensorContainer>
,这意味着 TypeScript 假定一个对象 TensorContainer
为您的数据集。
解决方案
为了帮助 TypeScript,您可以在创建 DataSet 时为其指定特定类型。当您正在读取内部具有多个属性的对象时,您可以扩展接口(interface) TensorContainerObject
.
代码示例
import { TensorContainerObject } from '@tensorflow/tfjs';
import { Dataset } from '@tensorflow/tfjs-data';
interface DataType extends TensorContainerObject {
xs: tf.Tensor;
ys: tf.Tensor;
}
const csvDataset = tf.data.csv(/* ... */) as any as Dataset<DataType>;
csvDataset.map(({xs, ys}) => {
// ...
});
不幸的是,由于 Tensorflow.js 对其数据集类型非常自以为是(因为联合用于默认 TensorContainer
),您必须使用 any
在将其转换为实际的 Dataset<DataType>
之前进行转换界面。
但是在那次转换之后,所有函数都在 DataSet
上工作喜欢map
自动知道正确的类型。而不是使用 tf.Tensor
上面,你甚至可以使用类似 tf.Tensor1D
的类型更具体。
替代解决方案:让错误消失
正如另一个答案中所述:如果您不关心类型和 TypeScript,而只想让错误消失,您可以将任何有问题的变量转换为 any
。 .
代码示例
csvDataset.map(({xs, ys}: any) => {
// ...
});
请记住,这会禁用对变量的任何类型检查。
关于javascript - 问题/错误 'Property ' 'xs' 在使用 tensorflow.js 的 Angular 项目中的类型 'TensorContainer' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781769/